Lecture 4 - Objects and Classes
Lecture 4 - Objects and Classes
CS 234: Object-Oriented
Programming in Java
Lecture – Objects and Classes
Aron Kondoro
University of Dar es Salaam
Introduction
• Objects and classes form the basis for object-oriented programming
in Java.
• Any object, phenomenon, or event that you wish to model and
represent in a program has
• Attributes
• Behaviour
University of Dar es Salaam
Analogy
• A car has many attributes
• Colour, number of doors etc
• A car has behaviours. It can
• move forward, steer (change direction) etc
University of Dar es Salaam
Attributes
• Attributes are the characteristics of public class Car {
// Attributes of the car
an object. String color;
String brand;
• In the case of a car, these could String model;
include color, brand, model, and Double engineSize;
}
engine size.
• These are represented in Java as
variables within a class.
University of Dar es Salaam
Behaviour public class Car {
// Method to start the car
• Behaviors are the actions that an public void startEngine() {
System.out.println("Engine
object can perform. started!");
• For a car, behaviors might include }
// Rav4
String nameRav4
Int numberOfDoorsRav4
University of Dar es Salaam
Why use classes?
• What if 200 RAV4s?
Terrible
University of Dar es Salaam
Why use classes?
Garage
University of Dar es Salaam
Why use classes?
More
Mechanic 1 Mechanic 2 Mechanic 3 mechanics…
197 more
cars…
Car 1 Car 2 Car 3
Garage
University of Dar es Salaam
Defining Classes
University of Dar es Salaam
Class Design
• When you design a class, think about the
objects that will be created from that class
type. Think about:
• things the object knows
• things the object does
• Things an object knows about itself are
called instance variables
• Things an object can do are called
methods
University of Dar es Salaam
Let’s declare a Car
}
University of Dar es Salaam
Car fields
public class Car {
public class Car { // Attributes of the car
String color = “Red”;
TYPE var_name;
String brand = “Toyota”;
TYPE var_name = some_value; String model = “Corolla”;
} Double engineSize = 1.8;
}
University of Dar es Salaam
Car methods
public class Car {
// Method to start the car
public void startEngine() {
System.out.println("Engine started!");
}
}
}
University of Dar es Salaam
Accessing fields
Object.METHODNAME([ARGUMENTS]);
// methods
void describe() {
System.out.println("Car type: " + type);
System.out.println("Car model: " + model);
System.out.println("Car color: " + color;
Constructors
University of Dar es Salaam
Constructors
• Typically, you can not call a method that belongs to another class until
you create an object of that class.
• For example, this is done by the following line in class CarTest:
• Keyword new creates a new object of the class specified to the right
of the keyword (i.e., Gar).
University of Dar es Salaam
Constructors
University of Dar es Salaam
Constructors
• Constructor name == the class name
• No return type – never returns anything
• Usually, initialize fields
• All classes need at least one constructor
University of Dar es Salaam
Constructors
• A constructor does look and feel a lot like a method, but it's not a
method. It has the code that runs when you instantiate an object.
• The only way to invoke a constructor is with the keyword new
followed by the class name.
• But where is the constructor? In our previous programs, we didn't
write It, who did?
• You can write a constructor for your class, but if you don't, the
compiler writes one for you!
University of Dar es Salaam
Car constructor
University of Dar es Salaam
Constructors
• It can be tedious to initialize all the variables in a class each time an
instance is created.
• Java allows objects to initialize themselves when they are created. This
automatic initialization is performed using a constructor.
• It is the constructor’s job to initialize the internal state of an object so that
the code creating an instance will have a fully initialized, usable object
immediately.
• If you don't put a constructor in your class, the compiler puts in a default
constructor. The default constructor is always a no-arg constructor.
public Car () { }
University of Dar es Salaam
Constructors
• You can have more than one constructor in your class, as long as the
argument lists are different. Having more than one constructor in a
class means you have overloaded constructors.
public Car () { };
public Car(int speed) { };
public Car(String type) { };
public Duck (String type, String model, String color) { };
University of Dar es Salaam
References vs Values
University of Dar es Salaam
Primitives vs References
• Primitive types are basic java types
• int, long, double, boolean, char, short, byte, float
• The actual values are stored in the variable
Name = “ist”
Name = “ist”
ist1 ist2
University of Dar es Salaam
next() hasNext()
nextDouble() hasNextDouble()
nextLine() hasNextLine()
University of Dar es Salaam
Scanner Demo
University of Dar es Salaam
Example of classes in the Java API
• String Class
• Various string related methods
• https://docs.oracle.com/en/java/javase/11
/docs/api/java.base/java/lang/String.html
• Import java.lang.String (optional)
char()
concat()
equals()
indexOf()
length()
substring()
University of Dar es Salaam
String Demo
University of Dar es Salaam
Example of classes in the Java API
• Math Class
• Performing computations
• https://docs.oracle.com/javase/8/docs/api
/java/lang/Math.html
• Import java.lang.Math (optional)
abs()
ceil()
floor()
max()
min()
pow()
random()
…
University of Dar es Salaam
Math Demo
University of Dar es Salaam
Exercises
• Date Program
• Create a Java program that models the date
• The date has three attributes: day, month, year.
• Create some objects Date and print their information
• Employee Program
• Java program that models employees
• Each employee has a name and surname and a monthly salary
• The program should create some employees and then increase their salary by
10%, and print their information.
University of Dar es Salaam
Exercises
• Invoice Program
• Java program that models and implements an invoice
• Each invoice has a number of parts and each part has a part number, a
description and a price.
• The program should create some invoices and print their information
University of Dar es Salaam
Exercises
• Heart Rate Program
• Java program that models heart rates, maximum heart rate and the maximum
and minimum target heart rate.
• The heart rate should be modelled with a class and should have name,
surname, birthYear and currentYear.
• The maximum heart rate MHR is based on the formula 220 - age.
• The minimum target HR is based on: 0.5 * MHR
• The maximum target HR is based on: 0.85 * MHR
• The program should create some objects of type Heart Rate and print their
information.
University of Dar es Salaam
Exercises
• Health Profile Program
• Java program that models health profile of persons
• Based on the previous program of Heart Rates: add the gender, height and
weight attribute
• Compute the person's BMI (body mass index): Weight * 703 / (getHeight() *
getHeight() );
• The program should create some objects of type Heart Rate and print their
information.