Chapter 2 - Defining Classes
Chapter 2 - Defining Classes
Defining Classes
REFERENCES
The content of this presentation is prepared based on:
oABSOLUTE JAVA™ 6th Edition Global Edition
oPowerPoint Lecture Slides for Absolute Java, Global Edition
oWebsites notes
OOP Approach
A Java program written using the OOP approach consists of objects from various classes
interacting with each other
A class is a type, and you can declare instances of a class type, called object
An object has both data and actions
oThe actions are called methods
oEach object can have different data values, but all objects of a class have the same
types of data and the same methods
CHAPTER 2 - DEFINING
4-6 CLASSES 6
Dr. Rayane El Sibai
Break down the program into entities (classes/objects - described with nouns)
Zoo
Animal Building
Visitor
Lions
Tigers Staff
Admin
Dogs
Animal care
Now, we can design the ZOO program using the OOP approach:
Class: Animal
Data members: size, age, color, and breed
Methods: eat, sleep, sit, and run
Now, for different values of the attributes (breed size, age, and color) in the class, we will
get different animals objects
Class Definition
A class definition specifies the data items and methods that all of its objects will have.
These data items and methods are called members of the object
Data items are called fields, instance variables, data members, or attributes
Instance variables declarations and methods definitions can be placed in any order
within the class definition Animal
breed
Data Fields/
size
Attributes/
age
Instance Variables
color
Class Members
eat()
sleep()
Methods
sit()
run()
Instance Variables
Instance variables (attributes) can be defined as follows:
String instanceVar1;
int instanceVar2;
Example
int year;
String month;
int day;
Methods
Method definitions are divided into two parts: a heading and a method body:
ClassName classVar;
Example
Date date1, date2;
The new operator must be used to create the object and associate it with its variable
name:
Example
date1 = new Date ();
date2 = new Date ();
Example
Date date1 = new Date ();
Date date2 = new Date ();
Example Example
int year; [Link] = “July”;
String month; [Link] = 4;
int day; [Link] = 1776;
Methods are invoked using the name of the calling object and the method name as
follows:
[Link]();
Example
[Link]();
In the method definition, all instance variables are understood to have a hidden
<calling object>. in front of them
[Link]("The day is: " + [Link] + ", the month is: " + [Link] + ",
the year is: " + [Link]);
[Link] = 3;
[Link] = "December";
[Link] = 2022;
[Link] = 10;
[Link] = "February";
[Link] = 2023;
Some programming languages include another kind of variable called a global variable -
The Java language does NOT have global variables
Local variables
A variable declared within a method definition is called a local variable
oAll variables declared in the main method are local variables
oAll method parameters are local variables
oIf two methods each have a local variable of the same name, they are still two
entirely different variables
oAll variables declared inside methods should be initialized
Instance variables
oAn instance variable is declared inside a class but outside of any method or block
oInstance variable has different copies for different objects
oAn instance variable is accessible throughout the class
Static variables
oAn static variable is declared inside a class but outside of any method or block
oAn static variable is accessible throughout the class
oStatic variables only have one single copy for the entire class
oUsed for storing constants
[Link](date1);
[Link]([Link]());
If you don’t override (redefine) the toString() method, [Link](Object) will print a
reference value of the object (its memory address)
•Overloading
•Constructors
Encapsulation means to encapsulate (bind, make a capsule of) all the attributes and
corresponding methods within one single capsule called class
Example:
We made a class named Date. Date has a day, month, and year. These are attributes,
and it has a writeOutput() method. So here we've encapsulated all these attributes and
methods of a date named Date.
To create an instance of Date, use: Date date1 = new Date();
To access all the attributes of Date, use the date1 variable
All the object’s data is contained and hidden in the object and access to it is restricted to
methods of that class
Data hiding is controlled in Java using access modifiers. In Java, hiding is done by using the
access modifier private
Code outside of the class cannot directly access class fields by names
Private fields of a specific class cannot be accessed by methods defined in another class
All access to a class fields takes place through its public methods
Implementing Encapsulation
To implement encapsulation in Java:
1. Make the instance variables private so that they cannot be accessed directly from
outside the class. You can only set and get values of these variables through the
methods of the class
2. Have getter and setter methods in the class to get and set the values of the fields
Example 1
public class Date { public class Demo {
public static void main(String[] args) {
public int year;
public String month; Date date1;
public int day; date1 = new Date();
} [Link] = 3;
[Link] = "December";
[Link] = 2022;
}
}
Example 2
public class Date { public class Demo {
public static void main(String[] args) {
public int year;
public String month; Date date1;
public int day; date1 = new Date();
[Link]("The day of date1 is: " +[Link]);
} [Link]("The month of date1 is: " +[Link]);
[Link]("The year of date1 is: " +[Link]);
}
}
Example 3
public class Date { public class Demo {
public static void main(String[] args) {
private int year;
private String month; Date date1;
private int day; date1 = new Date();
} [Link] = 3;
[Link] = "December";
[Link] = 2022;
}
}
Example 4
public class Date { public class Demo {
public static void main(String[] args) {
private int year;
private String month; Date date1;
private int day; date1 = new Date();
[Link]("The day of date1 is: " +[Link]);
} [Link]("The month of date1 is: " +[Link]);
[Link]("The year of date1 is: " +[Link]);
}
}
Implementing Encapsulation
To implement encapsulation in Java:
1. Make the instance variables private so that they cannot be accessed directly from
outside the class. You can only set and get values of these variables through the
methods of the class
2. Have getter and setter methods in the class to get and set the values of the fields
private
data
Example
getDay(), getMonth(), getYear()
Getter - Example
public class Date { public class Demo {
private int year; public static void main(String[] args) {
private String month;
private int day; Date date1;
date1 = new Date();
public int getYear() { [Link]("The day of date1 is: " +[Link]());
return year; } [Link]("The month of date1 is: " +[Link]());
[Link]("The year of date1 is: " +[Link]());
public String getMonth() { }
return month; } }
Setter - Example
public class Date { public class Demo {
private int year; public static void main(String[] args) {
private String month;
private int day; Date date1;
date1 = new Date();
public void setYear(int year) { [Link](3);
[Link] = year; } [Link](“January”);
[Link](2022);
public void setMonth(String month) { }
[Link] = month; } }
Are the accessor and mutator methods equivalent to making the instance variables
public?
Example
public class Date {
•Constructors
Method Signature
A signature consists of the name of a method together with its parameter list
In Java, two or more methods may have the same name inside the same class if they
differ in their signatures
▪ different number of parameters
▪ different types of parameters
▪ order of parameters
These methods are called overloaded methods and this feature is called method
overloading
oThe return types of the previous methods are not the same
oIt is because method overloading is not associated with return types
oOverloaded methods may have the same or different return types, but they must
differ in parameters
Overloading Example 1
Overloading by changing the number of parameters
Output
Overloading Example 2
Overloading by changing the type of parameters
Output
ClassName(anyParameters){
//code that initializes instance variables
}
The name of the constructor and its parenthesized list of arguments (if any) must follow the new
operator
The new operator creates a new instance and returns the address of the newly created object: It
allocates memory for the object
Attention: A constructor cannot be invoked like an ordinary method
}
}
Constructors Types
Constructors Types
Default
Non-default constructor
constructor
Default Constructor
A default constructor creates an object and sets the instance variables equal to default values
• boolean types are initialized to false
• Other primitives are initialized to the zero of their type
• Class types are initialized to null
• Default values can also be the values specified when declaring instance variables
If you add no constructor definitions to your class, then Java automatically creates the default
constructor
public Date(){ public Date(){
year = 0;
month = null; }
day = 0;
}
Non-Default Constructor
To initialize instance variables to specific values, you need to define your own
constructor
public Date(int y, int d){ public Date(int year, String month, int day){
year = y; [Link] = year;
day = d; [Link] = month;
} [Link] = day;
}
Constructors - Example
Default
public Date(){ public Date(int year, String month, int day){
constructor
year = 0; [Link] = year;
month = null; [Link] = month;
day = 0; [Link] = day; With
} } arguments
No arguments constructor
public Date(){
constructor
year = 2020; public Date(int y, int d){
month = “July”; year = y;
day = 12; day = d;
} }
}
}
Date date1;
date1 = new Date();
date1 = new Date(2021, “August”, 21);
}
}
Date date1;
date1 = new Date();
[Link](2023, “December”, 20);
}
}
It is even possible for one constructor to invoke another (See Chapter 4 - Inheritance)
A final variable must be always initialized, either at the declaration time, or in the constructor of the class
public Person(){
BIRTH_YEAR = 2023;
}
}