IT2.
4
Software Development
Fundamentals
07. Classes and Objects Mohammed
AbuJarour
21.11.24
* SUBJECT TO CHANGE
Plan
# Date Topic # Date Topic
1 10.10.24 Introduction to Software Development 7 21.11.24 Objects, Classes & Inheritance
Program logic: Flowcharts
8 28.11.24 Objects, Classes & Inheritance
2 17.10.24 Program logic: Pseudocode
9 05.12.24 Special (Java) features and
3 24.10.24 Introduction to Java Collections
Variables and Operators
10 12.12.24 I/O and Files
4 30.10.24 Selection and Iteration
11 19.12.24 GUI 1/2
5 07.11.24 Methods and Testing
6 14.11.24 Arrays and References 12 09.01.25 GUI 2/2
Mohammed AbuJarour – Classes and Objects 21.11.24 2
Java is an
object-oriented programming language
• What does this mean?
o Everything is encapsulated in special constructs, called classes
Mohammed AbuJarour – Classes and Objects 21.11.24 3
Classes as Data Types
Built-in data types: simple types & arrays
// ...
A simple data type
String name = "John Doe"; holds a single piece
int age = 33; of information
boolean isPrivate = true;
double salary = 5938.22; An array stores a
collection of items of
the same data type
char [] allowedSpecialChars = {'!', '$', '_', '.’};
// ...
Mohammed AbuJarour – Classes and Objects 21.11.24 5
How can a complex (user-defined) data type be
represented?
TYPE? javaBook =
title: "Java in Two Semesters"
authors: "Quentin Charatan", "Aaron Kans"
publisher: "Springer"
year: 2019
price: 43.5
ISBN: "978-3-319-99420-8"
Mohammed AbuJarour – Classes and Objects 21.11.24 6
Structs and records
• Earlier languages such as C struct Book { // Structure declaration
and Pascal allows us to int year; // Member (int variable)
char title[100]; // Member (String variable)
create a type that allowed
double price; // Member (double variable)
more than one piece of
// ...
information to be held
}; // End the structure with a semicolon
• Such types were known by
various names in different
languages, the most
common being structure and
record.
Mohammed AbuJarour – Classes and Objects 21.11.24 7
The Java approach
Class
User-defined Data Type Book Attributes
String title = "Java in Two Semesters";
DATA String[] authors = {"Quentin Charatan", "Aaron Kans"};
Elements String publisher = "Springer";
int year = 2019;
double price = 43.5;
String ISBN = "978-3-319-99420-8";
Methods
void borrow(){}
Behavior void buy(){}
boolean isAvailable(){}
Mohammed AbuJarour – Classes and Objects 21.11.24 8
Classes and Objects
Classes and Objects
• A class is a blueprint, or template, from which objects are generated, whereas an
object refers to an individual instance of that class
Class Object Object Object Object
Cupcake tin
Mohammed AbuJarour – Classes and Objects 21.11.24 10
Classes and Objects
Same type, categoy, class, etc. Same type, categoy, class, etc.
Object Object Object Object Object Objects
Lines Vectors by Vecteezy https://www.vecteezy.com/free-vector/lines
Mohammed AbuJarour – Classes and Objects 21.11.24 11
Classes and Objects
• Object-oriented programming
consists of defining one or more
classes that may interact with each
other.
• Many objects can be generated from
a single class template
Mohammed AbuJarour – Classes and Objects 21.11.24 12
Classes and Objects
class Car { class CarFactory {
private String color; public static void main(String[] args)
private int numberOfSeats; {
Car vw = new Car();
// ... vw.setColor("Black");
public String getColor() {
return color; Car ford = new Car();
} ford.setColor("White");
}
public void setColor(String newColor) { }
color = newColor;
}
}
Mohammed AbuJarour – Classes and Objects 21.11.24 13
Rectangle class
public class Main { class Rectangle {
public static void main(String[] args) { /*
int width;
Black box.
int height;
Rectangle whiteRectangle; By someone else
Rectangle smallRectangle;
*/
Rectangle abc;
}
}
}
Mohammed AbuJarour – Classes and Objects 21.11.24 14
Rectangle class
• Rectangle whiteRectangle;
• Declare an object (whiteRectangle) of Computer Memory Java Code
the class (Rectangle)
Rectangle whiteRectangle;
• This declaration creates a variable that
whiteRectangle
holds a reference to an object, rather
than the object itself
Mohammed AbuJarour – Classes and Objects 21.11.24 15
?
• How is memory for the Rectangle object going to be created, and how
is it going to be linked to the reference whiteRectangle?
Mohammed AbuJarour – Classes and Objects 21.11.24 16
Constructors
• An object is referred to as an • The constructor is a method that
instance of a class always has the same name as the
class.
• The process of creating an object is
referred to as instantiation. • When you create a new object, this
special method is always called.
• In order to create an object, we use a
very special method of the class
called a constructor.
Mohammed AbuJarour – Classes and Objects 21.11.24 17
Constructors
• The constructor’s task is to reserve • At the instantiation time, I need to
some space in the computer’s provide the minimum information that
memory just big enough to hold the can make a thing belong to this
required object category, e.g., class
• A constructor can be defined to do
other things, as well as reserve
memory, such as attribute
assignment, input validation,
initialization, etc.
Mohammed AbuJarour – Classes and Objects 21.11.24 18
Objects in memory
• What is the minimum set of information needed to create a Rectangle?
o width and height
o Rectangle(7.5, 12.4);
• This statement reserves space in memory for a new Rectangle
• Rectangle whiteRectangle = new 12.4);
Rectangle(7.5,
• Using the constructor with the keyword new reserves memory for a new
Rectangle object.
Mohammed AbuJarour – Classes and Objects 21.11.24 19
Creating a new object
Computer Memory Java Code
whiteRectangle
Rectangle whiteRectangle;
(Stores location of
object)
whiteRectangle = new
Space for the new Rectangle(7.5, 12.4);
whiteRectangle
object
Mohammed AbuJarour – Classes and Objects 21.11.24 20
Analogy
Walls
Columns
Windows
Doors
Floors
Interiors
.
.
.
Mohammed AbuJarour – Classes and Objects 21.11.24 21
Encapsulation
• When a class is written, we make • In order to use a class, all we need to
sure that no program can assign know are details about its methods:
values to the attributes directly. their names, what the methods are
• In this way, the data in the class is expected to do, and also their inputs
protected. and outputs.
• The implementation remains
• Protecting data in this way is known
as encapsulation. unknown to us (Black-box)
• The only way to interact with the data
is via the methods of the class.
Mohammed AbuJarour – Classes and Objects 21.11.24 22
Method Description Inputs Output
Rectangle The constructor Two items of data, both of Not
type double, representing applicable
the length and height of
the oblong respectively
setLength Sets the value of the length of An item of type double None
the rectangle
setHeight Sets the value of the height of An item of type double None
the rectangle
getLength Returns the length of the None An item of
rectangle type double
getHeight Returns the height of the None An item of
rectangle type double
calculateArea Calculates and returns the area None An item of
of the rectangle type double
calculatePerimeter Calculates and returns the None An item of
perimeter of the rectangle type double
Mohammed AbuJarour – Classes and Objects 21.11.24 23
The dot operator
• Assigning values to an object’s attributes is done initially via the constructor
• We might also want to be able to change these values during the course of a
program.
• We typically provided methods called setLength and setHeight so that we can write
values to the attributes.
• We typically provide methods to return, or read, the values of the attributes.
These we have called getLength and getHeight.
• To call a method of one class from another class, we use the name of the object
together with the name of the method separated by a full stop (often referred to
as the dot operator).
• int x = keyboard.nextInt();
Mohammed AbuJarour – Classes and Objects 21.11.24 24
Example
public class Main {
public static void main(String[] args) {
Rectangle whiteRectangle = new Rectangle(7.5, 12.4);
System.out.println("Width : " + whiteRectangle.getWidth());
System.out.println("Height : " + whiteRectangle.getHeight());
System.out.println("Area : " + whiteRectangle.calculateArea());
System.out.println("Perimeter : " + whiteRectangle.calculatePerimeter());
whiteRectangle.setWidth(3);
whiteRectangle.setHeight(2);
System.out.println("Width : " + whiteRectangle.getWidth());
System.out.println("Height : " + whiteRectangle.getHeight());
System.out.println("Area : " + whiteRectangle.calculateArea());
System.out.println("Perimeter : " + whiteRectangle.calculatePerimeter());
}
}
Mohammed AbuJarour – Classes and Objects 21.11.24 25
this
• We calling the methods from within a • In Java, there exists a special
class, we use the name of the keyword this.
method on its own.
• The keyword this is used within a
• In actual fact, what we were doing is class when we wish to refer to an
form of shorthand. attribute of the class itself, rather
demoMethod(x); than an attribute of some other class
this.demoMethod(x);
Mohammed AbuJarour – Classes and Objects 21.11.24 26
null
• Just as you cannot use a variable that has if(whiteRectangle!=null) {
not been initialized, you cannot call a whiteRectangle.setWidth(3);
method of an object if no storage is whiteRectangle.setHeight(2);
allocated for the object }
• Be careful!
• This would cause a problem at run-time.
• In Java, when a reference is first created
without assigning it to a new object in the
same line, it is given a special value of
null; a null value indicates that no storage
is allocated
Mohammed AbuJarour – Classes and Objects 21.11.24 27
Java Objects
Initializing Attributes
• Java always initializes class • It is a good programming practice to
attributes. give an initial value to class
attributes, rather than leave it to the
• Numerical attributes, such as int and
double, are initialized to zero; compiler.
• One technique you could use is to
• boolean attributes are initialized to
give an attribute some special initial
false
value (such as a negative value) to
• Objects are initialized to null. indicate to the user of this class that
• char attributes are given an initial this attribute had not been set.
Unicode value of zero
Mohammed AbuJarour – Classes and Objects 21.11.24 29
Initializing Attributes
class Employee {
//The salary cannot be zero
private double salary =-1;
//The bonus could be zero
private double bonus;
//Better to explicitly set it to zero
private double bonus = 0;
// ...
Mohammed AbuJarour – Classes and Objects 21.11.24 30
Java Constructors
• A constructor in Java is a special method • All classes have constructors by default:
that is used to initialize objects. if you do not create a class constructor
yourself, Java creates one for you.
• The constructor is called when an object
However, then you are not able to set
of a class is created (i.e., instantiated).
initial values for object attributes.
• It can be used to set initial values for
• If you define at least one constructor, the
object attributes
default constructor will no longer be
• The constructor name must match the provided
class name, and it cannot have a return
• You can define as many constructors as
type (like void).
you need
Mohammed AbuJarour – Classes and Objects 21.11.24 31
Java Constructors
class Machine {
private double price; // Create a class attribute
// Create a class constructor for the Machine class
public Machine(double p) {
price = p; // Set the initial value for the class attribute price
}
public void print(){
System.out.println("This machine costs " + price);
}
}
public class Main{
public static void main(String[] args) {
Machine drill = new Machine(85.7); // Create an object of class Machine (This will call the constructor)
drill.print();
}
}
Mohammed AbuJarour – Classes and Objects 21.11.24 32
Java Constructors
class Machine {
private double price; // Create a class attribute
/*
public Machine(double p) {
price = p; // Set the initial value for the class attribute price
}
*/
public void setPrice(double price) {
this.price = price;
}
public void print(){
System.out.println("This machine costs " + price);
}
}
public class Main{
public static void main(String[] args) {
Machine drill = new Machine(85.7); // Error: expected 0 arguments, but found 1
Machine drill2 = new Machine(); // Create an object of class Machine (calls default constructor)
drill2.setPrice(85.7);
drill2.print();
}
}
Mohammed AbuJarour – Classes and Objects 21.11.24 33
Pass objects as parameters
public class Main{
public static void main(String[] args) {
Machine drill = new Machine(); // Create an object of class Machine
drill.setPrice(100);
drill.print();
This machine costs 100.0
doMaintenance(drill); This machine costs 95.0
drill.print();
}
private static void doMaintenance(Machine machine) {
// ... magic
machine.setPrice(machine.getPrice()*0.95);
}
}
Mohammed AbuJarour – Classes and Objects 21.11.24 34
Pass objects as parameters
• Passing an object as a parameter will pass a reference to the object
• This means the method has access to the original object not a copy of the object
• Any changes applied in the called method on the passed object will affect the
original object
Mohammed AbuJarour – Classes and Objects 21.11.24 35
Java Modifiers
Two groups of modifiers
• Two groups of modifiers:
1. Access Modifiers: control the access level
2. Non-Access Modifiers: do not control
access level, but provide other functionality
Mohammed AbuJarour – Classes and Objects 21.11.24 37
Access Modifiers – for classes
Modifier Description
public The class is accessible by any other class
<<default>> The class is only accessible by classes in the same package.
This is used when you don’t specify a modifier.
Mohammed AbuJarour – Classes and Objects 21.11.24 38
Access Modifiers – for attributes, methods
and constructors
Modifier Description
public The code is accessible for all classes
private The code is only accessible within the declared class
<<default>> The code is only accessible in the same package.
This is used when you don’t specify a modifier.
protected The code is accessible in the same package and subclasses.
Mohammed AbuJarour – Classes and Objects 21.11.24 39
Non-Access Modifiers – for classes
Modifier Description
final The class cannot be inherited by other classes
abstract The class cannot be used to create objects
Mohammed AbuJarour – Classes and Objects 21.11.24 40
Non-Access Modifiers – for attributes and methods
Modifier Description
final Attributes and methods cannot be overridden/modified
static Attributes and methods belongs to the class, rather than an object
abstract Can only be used in an abstract class, and can only be used on methods.
The method does not have a body. The body is provided by the subclass
(inherited from).
transient Attributes and methods are skipped when serializing the object containing them
synchronized Methods can only be accessed by one thread at a time
volatile The value of an attribute is not cached thread-locally, and is always read from
the “main memory”
Mohammed AbuJarour – Classes and Objects 21.11.24 41
Non-Access Modifiers – for attributes and methods
• If you don’t want the ability to override existing attribute values, declare attributes
as final
public class Main {
final int x = 10;
final double PI = 3.14;
public static void main(String[] args) {
Main myObj = new Main();
myObj.x = 50; // will generate an error: cannot assign a value to a final variable
myObj.PI = 25; // will generate an error: cannot assign a value to a final variable
System.out.println(myObj.x);
}
}
Mohammed AbuJarour – Classes and Objects 21.11.24 42
Non-Access Modifiers – for attributes and methods
• A static method means that it can be accessed without creating an object of the class
class GradeConvertor{
public static double convertMark2GermanGrade(double mark){
double grade = 5.0;
//... if then else
return grade;
}
}
public class Main{
public static void main(String[] args) {
double grade = GradeConvertor.convertMark2GermanGrade(94.5);
System.out.println(grade);
}
}
Mohammed AbuJarour – Classes and Objects 21.11.24 43
Non-Access Modifiers – for attributes and methods
• An abstract method belongs to an abstract class, and it does not public class Main {
have a body. The body is provided by the subclass public static void main(String[] args) {
// create an object of the Student class
(which inherits attributes and methods
abstract class Person { from Person)
public String fname = "John"; Student myObj = new Student();
public int age = 24;
// abstract method System.out.println("Name: " + myObj.fname);
public abstract void studyOrWork(); System.out.println("Age: " + myObj.age);
} System.out.println("Graduation Year: " + myObj.graduationYear);
myObj.studyOrWork(); // call abstract method
// Subclass (inherit from Person) }
class Student extends Person { }
public int graduationYear = 2024;
public void studyOrWork() {
// provide the body of the abstract method here
System.out.println("Studying all day long");
}
}
Mohammed AbuJarour – Classes and Objects 21.11.24 44
Encapsulation
• Encapsulation makes sure that “sensitive” data is hidden from users.
• To achieve this, you must:
o declare class variables/attributes as private
o provide public get and set methods to access and update the value of a private variable
• The get method returns the variable value, and the set method sets the value.
• Syntax for both is that they start with either get or set, followed by the name of the
variable, with the first letter in upper case
Mohammed AbuJarour – Classes and Objects 21.11.24 45
Encapsulation
public class Person {
// private = restricted access
private String name;
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String newName) {
this.name = newName;
}
}
Mohammed AbuJarour – Classes and Objects 21.11.24 46
Why Encapsulation?
• Better control of class attributes and methods
• Class attributes can be made read-only (if you only use the get method), or write-
only (if you only use the set method)
• Flexible: the programmer can change one part of the code without affecting other
parts
• Increased security of data
Mohammed AbuJarour – Classes and Objects 21.11.24 47
Source
Quentin Charatan and Aaron Kans
Java in Two Semesters
Fourth Edition
Chapter 7: Classes and Objects
Mohammed AbuJarour – Classes and Objects 21.11.24 48
Exercises
Lab 7.1
• Write a Java program to create a
class called Cat with instance
variables name and age.
Implement a default constructor
that initializes the name to “Unknown”
and the age to 0.
Print the values of the variables.
Mohammed AbuJarour – Classes and Objects 21.11.24 50
Lab 7.2
• Write a Java program to create a
class called Dog with instance
variables name and color.
Implement a parameterized
constructor that takes name and
color as parameters and initializes
the instance variables.
Print the values of the variables.
Mohammed AbuJarour – Classes and Objects 21.11.24 51
Lab 7.3
• Write a Java program to create a class called
Book with instance variables title, author, and
price. Implement a default constructor and
two parameterized constructors:
o One constructor takes title and author as parameters.
o The other constructor title title, author, and price as
parameters.
• Print the values of the variables for each
constructor.
Mohammed AbuJarour – Classes and Objects 21.11.24 52
Lab 7.4
• Write a Java program to create a class
called Student with instance variables
studentId, studentName, and grade.
Implement a default constructor and a
parameterized constructor that takes all
three instance variables. Use constructor
chaining to initialize the variables.
Print the values of the variables.
Mohammed AbuJarour – Classes and Objects 21.11.24 53
Lab 7.5
• Write a Java program to create a class
called IDGenerator with a static variable
nextID and a static method generateID()
that returns the next ID and increments
nextID.
Demonstrate the usage of generateID in
the main method.
Mohammed AbuJarour – Classes and Objects 21.11.24 54
Lab 7.6
• Write a Java program to create a class
called BankAccount with private instance
variables accountNumber and balance.
Provide public getter and setter
methods to access and modify these
variables.
Mohammed AbuJarour – Classes and Objects 21.11.24 55
Lab 7.7
30 Minutes
• Develop a model for a program to manage soccer games for teams along their
players.
• Keep it simple
• What are the classes?
• What are their attributes?
• What are their methods?
Mohammed AbuJarour – Classes and Objects 21.11.24 56