Introduction to Object Oriented Programming
Seoul National University of Science and Technology
Information Technology Management
Lecture slides index
May 11, 2025
You’re familiar with the concepts of class, object, constructor, object methods, and object variables.
You understand that a class defines an object’s methods and that the values of instance (object) variables are object-specific.
You know how to create classes and objects, and know how to use objects in your programs.
ArrayList
ArrayList
is a class offered by Java, and we’ve made use of objects instantiated from it in our programs.ArrayList
object named integers
is created and some integers are added to it.// we create an object from the ArrayList class named integers
ArrayList<Integer> integers = new ArrayList<>();
// let's add the values 15, 34, 65, 111 to the integers object
integers.add(15);
integers.add(34);
integers.add(65);
integers.add(111);
// we print the size of the integers object
System.out.println(integers.size());
new
keyword.The exercise template comes with a ready-made class named Account
.
The Account
object represents a bank account that has balance (i.e.
one that has some amount of money in it).
Write a program that creates an account with a balance of 100.0, deposits 20.0 in it, and finally prints the balance.
(user input) NB!
Perform all the operations in this exact order.
public class Account {
private double balance;
private String owner;
public Account(String owner, double balance) {
this.balance = balance;
this.owner = owner;
}
public void deposit(double amount) {
this.balance = this.balance + amount;
}
public void withdrawal(double amount) {
this.balance = this.balance - amount;
}
public double saldo() {
return this.balance;
}
@Override
public String toString() {
return this.owner + " balance: " + this.balance;
}
}
Account mariosAccount = new Account("Mario's account", 100.00);
Account mariosSwissAccount = new Account("Mario's account in Switzerland", 1000000.00);
System.out.println("Initial state");
System.out.println(mariosAccount);
System.out.println(mariosSwissAccount);
mariosAccount.withdraw(20);
System.out.println("The balance of Mario's account is now: " + mariosAccount.balance());
mariosSwissAccount.deposit(200);
System.out.println("The balance of Mario's other account is now: " + mariosSwissAccount.balance());
System.out.println("End state");
System.out.println(mariosAccount);
System.out.println(mariosSwissAccount);
The Account
from the previous exercise class is also available in this exercise.
Write a program that:
"Matthews account"
with the balance 1000"My account"
with the balance 0A class specifies what the objects instantiated from it are like.
We’ll now familiarize ourselves with creating our own classes and defining the variable that belong to them.
A class is defined to represent some meaningful entity, where a “meaningful entity” often refers to a real-world object or concept.
If a computer program had to process personal information, it would perhaps be meaningful to define a separate class Person
consisting of methods and attributes related to an individual.
Let’s begin.
We’ll assume that we have a project template that has an empty main program:
In NetBeans, a new class can be created by going to the projects section located on the left, right-clicking new, and then java class.
The class is provided a name in the dialog that opens.
As with variables and methods, the name of a class should be as descriptive as possible.
It’s usual for a class to live on and take on a different form as a program develops.
As such, the class may have to be renamed at some later point.
Person
.Person.java
.Person.java
file initially contains the class definition (user input) public class Person and the curly brackets that confine the contents of the class.Person
has been added to the Test project.name
and an age
.Person
class has a name
and an age
.public class Person {
.name
and age
, which are able to hold object-specific values.dogattributes
.Dog
in this exercise, and press the finish button.Dog
.private String name
,private String breed
and private int age
to the class.ArrayList
, using the new
keyword.new Person ("Ada")
).this.age = 0
.age
of the newly created object (i.e., “this” object’s age) to 0.this.name = initialName
likewise assigns the string passed as a parameter to the instance variable name
of the object created.Room
.private String code
and private int seats
to the class.public Room(String classCode, int numberOfSeats)
through which values are assigned to the instance variables.If the programmer does not define a constructor for a class, Java automatically creates a default one for it.
A default constructor is a constructor that doesn’t do anything apart from creating the object.
The object’s variables remain uninitialized (generally, the value of any object references will be null
, meaning that they do not point to anything, and the values of primitives will be 0
)
For example, an object can be created from the class below by making the call new Person()
new Person()
would cause an error, as Java cannot find a constructor in the class that has no parameters.public class Person {
private String name;
private int age;
public Person(String initialName) {
this.age = 0;
this.name = initialName;
}
public void printPerson() {
System.out.println(this.name + ", age " + this.age + " years");
}
}
public void
, since the method is intended to be visible to the outside world (public
), and it does not return a value (void
).We’ve used the modifier static
in some of the methods that we’ve written.
The static
modifier indicates that the method in question does not belong to an object and thus cannot be used to access any variables that belong to objects.
Going forward, our methods will not include the static
keyword if they’re used to process information about objects created from a given class.
If a method receives as parameters all the variables whose values it uses, it can have a static
modifier.
printPerson
.public
modifier, the method name is prefixed with a plus sign.void
.printPerson
contains one line of code that makes use of the instance variables name
and age
– the class diagram says nothing about its internal implementations.this
.Create a class named Whistle
.
Add the variable private String sound
to the class.
After that, create the constructor public Whistle(String whistleSound)
, which is used to create a new whistle that’s given a sound.
Then create the method public void sound()
that prints the whistle’s sound.
Create a class named Door
.
The door does not have any variables.
Create for it a constructor with no parameters (or use the default constructor).
After that, create a public void knock()
method for the door that prints the message “Who’s there?” when called.
The door should work as follows.
Product
that represents a store product.public Product (String initialName, double initialPrice, int initialQuantity)
public void printProduct()
that prints product information in the following format:banana
, with a price of 1.1
, and a quantity of 13
.public class Person {
private String name;
private int age;
public Person(String initialName) {
this.age = 0;
this.name = initialName;
}
public void printPerson() {
System.out.println(this.name + ", age " + this.age + " years");
}
// growOlder() method has been added
public void growOlder() {
this.age = this.age + 1;
}
}
Person
class just as the printPerson
method was.age
by one.growOlder
The program’s print output is as follows:
Sample Output
this.age = 0;
is executed in the constructor).ada
object’s growOlder
method is called twice.growOlder
public class Person {
private String name;
private int age;
public Person(String initialName) {
this.age = 0;
this.name = initialName;
}
public void printPerson() {
System.out.println(this.name + ", age " + this.age + " years");
}
// no one exceeds the age of 30
public void growOlder() {
if (this.age < 30) {
this.age = this.age + 1;
}
}
}
decreasingCounter
.decrement()
method in the class body in such a way that it decrements the value
variable of the object it’s being called on by one.
public void reset()
for the counter that resets the value of the counter to 0.public class DecreasingCounter {
private int value; // a variable that remembers the value of the counter
public DecreasingCounter(int initialValue) {
this.value = initialValue;
}
public void printValue {
System.out.println("value: " + this.value);
}
public void decrement() {
// write the method implementation here
// the aim is to decrement the value of the counter by one
}
// and the other methods go here
}
Create the class Debt
that has double-typed instance variables of balance
and interestRate
.
The balance and the interest rate are passed to the constructor as parameters public Debt(double initialBalance, double initialInterestRate)
.
In addition, create the methods public void printBalance()
and public void waitOneYear()
for the class.
The method printBalance prints the current balance, and the waitOneYear method grows the debt amount.
The debt is increased by multiplying the balance by the interest rate.
Once you get the program to work, try out the previous example with the interest rates of the early 1990s recession when the interest rates were as high as 15-20% - try swapping the interest rate in the example above with 1.20
and see what happens.
void
keyword with the type of the variable to be returned.grade
that always returns an integer-type (int
) variable (in this case, the value 10).int
type variable of value 10 when called.public static void main(String[] args) {
Teacher first = new Teacher();
Teacher second = new Teacher();
Teacher third = new Teacher();
double average = (first.grade() + second.grade() + third.grade()) / 3.0;
System.out.println("Grading average " + average);
}
void
modifier as the type of variable to be returned.
int
modifier as the type of variable to be returned.
String
modifier as the type of the variable to be returned
double
modifier as the type of the variable to be returned.
returnAge
method that returns the person’s age.public class Person {
private String name;
private int age;
public Person(String initialName) {
this.age = 0;
this.name = initialName;
}
public void printPerson() {
System.out.println(this.name + ", age " + this.age + " years");
}
public void growOlder() {
if (this.age < 30) {
this.age = this.age + 1;
}
}
// the added method
public int returnAge() {
return this.age;
}
public class Main {
public static void main(String[] args) {
Person mina = new Person("Mina");
Person mike = new Person("Mike");
mina.growOlder();
mina.growOlder();
mike.growOlder();
System.out.println("Mina's age: " + mina.returnAge());
System.out.println("Mike's age: " + mike.returnAge());
int combined = mina.returnAge() + mike.returnAge();
System.out.println("Mina's and Mike's combined age " + combined + " years");
}
}
Create a class called Song
.
The song has the instance variables name
(string) and length
in seconds (integer).
Both are set in the public Song(String name, int length)
constructor.
Also, add to the object the methods public String name()
, which returns the name of the song, and public int length()
, which returns the length of the song.
The class should work as follows.
Song garden = new Song("In The Garden", 10910);
System.out.println("The song " + garden.name() + " has a length of " + garden.length() + " seconds.");
Create a film class with the instance variables name
(String) and ageRating
(int).
Write the constructor public Film(String filmName, int filmAgeRating)
for the class, and also the methods public String name()
and public int ageRating()
.
The first of these returns the film title and the second returns its rating.
Below is an example use case of the class.
Film chipmunks = new Film("Alvin and the Chipmunks: The Squeakquel", 0);
Scanner reader = new Scanner(System.in);
System.out.println("How old are you?");
int age = Integer.valueOf(reader.nextLine());
System.out.println();
if (age >= chipmunks.ageRating()) {
System.out.println("You may watch the film " + chipmunks.name());
} else {
System.out.println("You may not watch the film " + chipmunks.name());
}
true
or false
:public static void main(String[] args) {
Person mina = new Person("Mina");
Person mike = new Person("Mike");
int i = 0;
while (i < 30) {
mina.growOlder();
i = i + 1;
}
mike.growOlder();
System.out.println("");
if (mike.isOfLegalAge()) {
System.out.print("of legal age: ");
mike.printPerson();
} else {
System.out.print("underage: ");
mike.printPerson();
}
if (mina.isOfLegalAge()) {
System.out.print("of legal age: ");
mina.printPerson();
} else {
System.out.print("underage: ");
mina.printPerson();
}
}
getName
method returns the instance variable name
to the caller.getVariableName
.public static void main(String[] args) {
Person pekka = new Person("Pekka");
Person antti = new Person("Antti");
int i = 0;
while (i < 30) {
pekka.growOlder();
i = i + 1;
}
antti.growOlder();
System.out.println("");
if (antti.isOfLegalAge()) {
System.out.println(antti.getName() + " is of legal age");
} else {
System.out.println(antti.getName() + " is underage");
}
if (pekka.isOfLegalAge()) {
System.out.println(pekka.getName() + " is of legal age");
} else {
System.out.println(pekka.getName() + " is underage ");
}
}
Gauge
.private int value
, a constructor without parameters (sets the initial value of the meter variable to 0), and also the following four methods:
public void increase()
grows the value
instance variable’s value by one. It does not grow the value beyond five.public void decrease()
decreases the value
instance variable’s value by one. It does not decrease the value to negative numbers.public int value()
returns the value
variable’s value.public boolean full()
returns true
if the instance variable value
has the value five. Otherwise, it returns false.toString
-methodprintPerson
method.toString
in Java.public class Person {
// ...
public String toString() {
return this.name + ", age " + this.age + " years";
}
}
toString
functions as printPerson
does.toString
-methodpublic static void main(String[] args) {
Person mina = new Person("Mina");
Person mike = new Person("Mike");
int i = 0;
while (i < 30) {
mina.growOlder();
i = i + 1;
}
mike.growOlder();
System.out.println(mike); // same as System.out.println(mike.toString());
System.out.println(mina); // same as System.out.println(mina.toString());
}
System.out.println
method requests the object’s string representation and prints it.toString
method returning the string representation does not have to be written explicitly, as Java adds it automatically.toString
-method works?As such, the call System.out.println(mike)
calls the toString
method of the mike
object and prints the string returned by it.
We can remove the now obsolete printPerson
method from the Person class.
print
method is defined for the class that creates the following string representation.Remove the print
method, and create a public String toString()
method for it, which returns the string representation shown above.
The class should function as follows.
Person
class once more.public class Person {
private String name;
private int age;
private int weight;
private int height;
public Person(String initialName) {
this.age = 0;
this.weight = 0;
this.height = 0;
this.name = initialName;
}
public void setHeight(int newHeight) {
this.height = newHeight;
}
public void setWeight(int newWeight) {
this.weight = newWeight;
}
public double bodyMassIndex() {
double heigthPerHundred = this.height / 100.0;
return this.weight / (heigthPerHundred * heigthPerHundred);
}
// ...
}
height
and weight
were added to the person.setHeight
and setWeight
methods.setVariableName
.public static void main(String[] args) {
Person carlos = new Person("Carlos");
Person hana = new Person("Hana");
carlos.setHeight(180);
carlos.setWeight(86);
hana.setHeight(175);
hana.setWeight(64);
System.out.println(carlos.getName() + ", body mass index is " + carlos.bodyMassIndex());
System.out.println(hana.getName() + ", body mass index is " + hana.bodyMassIndex());
}
setHeight
method sets the value of the parameter newHeight
to the instance variable height
:height
in the method refers specifically to a parameter named height and this.height
to an instance variable of the same name.height
variable received as a parameter to the value it already contains:
Create a class Multiplier that has a:
public Multiplier(int number)
.public int multiply(int number)
which returns the value number
passed to it multiplied by the number
provided to the constructor.You also need to create an instance variable in this exercise.
An example of the class in use:
Multiplier multiplyByThree = new Multiplier(3);
System.out.println("multiplyByThree.multiply(2): " + multiplyByThree.multiply(2));
Multiplier multiplyByFour = new Multiplier(4);
System.out.println("multiplyByFour.multiply(2): " + multiplyByFour.multiply(2));
System.out.println("multiplyByThree.multiply(1): " + multiplyByThree.multiply(1));
System.out.println("multiplyByFour.multiply(1): " + multiplyByFour.multiply(1));
toString
to also tell of a person’s body mass index, the object’s own bodyMassIndex
method should be called in the toString
method:public String toString() {
return this.name + ", age " + this.age + " years, my body mass index is " + this.bodyMassIndex();
}
bodyMassIndex()
, whereby no emphasis is placed on the fact that the object’s own bodyMassIndex method is being called:Create a class Statistics
that has the following functionality (the file for the class is provided in the exercise template):
addNumber
adds a new number to the statisticsgetCount
tells the number of added numberssum
tells the sum of the numbers added (the sum of an empty number statistics object is 0)average
tells the average of the numbers added (the average of an empty number statistics object is 0Then, write a program that asks the user for numbers until the user enters -1.
Statistics
objects to calculate the sums.public class Statistics {
private int count;
private int sum;
public Statistics() {
// initialize the variables count and sum here
}
public void addNumber(int number) {
// write code here
}
public int getCount() {
// write code here
}
public int sum() {
// write code here
}
public double average() {
// write code here
}
}
You’re familiar with the concepts of class, object, constructor, object methods, and object variables.
You understand that a class defines an object’s methods and that the values of instance (object) variables are object-specific.
You know how to create classes and objects, and know how to use objects in your programs.
Computer Language