Chapter 2 - Defining Classes
Chapter 2 - Defining Classes
Classes
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
Dr. Abed EL Safadi
OOP Approach
CHAPTER 2 - DEFINING CLASSES 64-6
objects of a certain kind Different objects can have different variables (attributes)
values Each house object can have its own color, floor tiles, home equipment,
etc.
Dr. Abed EL Safadi
Visitor
Lions
Staff
Tigers
Admin Animal care
Dogs
Example for the class Animal: color, age, breed, size, etc.
Dr. Abed EL Safadi
CHAPTER 2 - DEFINING CLASSES 12
14
Now, for different values of the attributes (
Class Definition
Dr. Abed EL Safadi
}
Instance variables (attributes) can be defined as follows: String instanceVar1;
int instanceVar2;
int year;
String month;
Instance Variables
Example
Method definitions are divided into two parts: a heading and a method body:
Dr. Abed EL Safadi
Methods
CHAPTER 2 - DEFINING CLASSES 20
void myMethod() Heading {
//code to perform some action Body
}
be combined as follows:
ClassName classVar = new ClassName();
Dr. Abed EL Safadi
objectName.instanceVar1
objectName.instanceVar2
Example
Methods are invoked using the name of the calling object and the method name
as
follows:
Dr. Abed EL Safadi
The Calling Object (2/4)
[Link]();
In the method definition, all instance variables are understood to have a
hidden
The
<calling object>. in front of themCHAPTER 2 - DEFINING CLASSES 27
[Link]("The day is: " + [Link] + ", the month is: " + [Link] +
", the year is: " + [Link]);
public class Demo { date2 = new Date(); [Link] = 3;
-
public static void main(String[] args) {
29
Date date1, date2;
date1 = new Date();
Example
[Link] = "December"; [Link]
= 2022;
[Link] = 10;
[Link] = "February"; [Link]
= 2023;
}
In the method definition, if an explicit name for the calling object is needed,
thekeyword this can be used
this must be used if a parameter or other local variable with the same name as
theinstance variables is used in the method. Otherwise, all instances of the
variable name
will be interpreted as localCHAPTER 2 - DEFINING CLASSES 31
Dr. Abed EL Safadi
When to use the this
Parameter?
The this Parameter - Example CHAPTER
2 - DEFINING CLASSES 32public void changeDate (int day, String month, int year){
public void changeDate (int day, String month, int year){ [Link] = day;
[Link] = month;
Dr. Abed EL Safadi
day = day;
month = month;
year = year;
}
[Link] = year;
}
Example of a
predefined class
CHAPTER 2 - DEFINING CLASSES 33 The
Scanner Class
Some programming languages include another kind of variable called a global variable
-
The Java language does NOT have global variables
Dr. Abed EL Safadi
two
entirely different variables oAll variables declared inside methods should be
initialized
Dr. Abed EL Safadi
Variables in Java (2/4)
CHAPTER 2 - DEFINING CLASSES 35
Instance variables
oAn instance variable is declared inside a class but outside of any method or
blockoInstance variable has different copies for different objects oAn instance
variable is accessible throughout the object
Dr. Abed EL Safadi
Safadi
In order to put the object into a usable state, its instance variables should be
}
Java expects certain methods to be in almost all classes
The purpose of the
One of these methods is called toString(), of type String
If you don’t override (redefine) the toString() method, [Link](Object) will print
a
reference value of the object (its memory address)
Dr. Abed EL Safadi
The Method toString (2/3)
[Link]([Link]());
•Overloading
•Constructors
Encapsulation means to encapsulate (bind, make a capsule of) all the
attributesandcorresponding methods within one single capsule called class We
has a day, month, and year. These are
made a class named Date. Date
attributes, method. So here we've encapsulated all
and it has a writeOutput()
Example:
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 Data hiding is controlled in Java using access modifiers. In Java,
methods of that class
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
Dr. Abed EL Safadi
Implementing EncapsulationTo
so that
implement encapsulation in Java: 1. Make the instance variables private
they cannot be accessed directly fromoutside the class. You can only set and get
setter methods in the class to get and set the values of the fieldsCHAPTER 2 - DEFINING
EL Safadi
Dr. Abed EL Safadi
Example 1
Example 2
}
}
Dr. Abed EL Safadi
Example 3
}
[Link] = 3;
[Link] = "December";
[Link] = 2022;
}
Date date1; }
date1 = new Date();
[Link]("The day of date1 is: " +[Link]);
[Link]("The month of date1 is: " +[Link]);
[Link]("The year of date1 is: " +[Link]);
Dr. Abed EL Safadi
Example 4
Implementing EncapsulationTo
so that
implement encapsulation in Java: 1. Make the instance variables private
they cannot be accessed directly fromoutside the class. You can only set and get
setter methods in the class to get and set the values of the fieldsCHAPTER 2 - DEFINING
CLASSES 52Dr. Abed EL Safadi
public methods are used to access the private data members fromoutside of the
classCHAPTER 2 - DEFINING CLASSES 53private
Dr. Abed EL Safadi
get data
set data
(accessor
(mutator
method) method)
public
public
public
method
method
method
data
Accessor (getter) methods allow the programmer to obtain the value of an
object's
instance variables The data can be accessed but not changed
Getter - Example
[Link]("The day of date1 is: " +[Link]());
[Link]("The month of date1 is: " +[Link]());
[Link]("The year of
date1 is: " +[Link]());
Dr. Abed EL Safadi
DEFINING CLASSES 56
[Link] = month; }
Dr. Abed EL Safadi
[Link] = day; }
Setter - Example
public class Date { private int year;
CHAPTER 2 - DEFINING CLASSES 57public class Demo { public static void main(String[] args) {
}
Dr. Abed EL Safadi
}
else{
[Link](“Your value is wrong!);
day = 0;
}
}
public/private
the classCHAPTER 2 - DEFINING CLASSES 61
Modifiers – Methods
The modifiers public and private before a method definition have a similar meaning If the
If the method is labeled
method is labeled public, there are no restrictions on its usage
Example
CHAPTER 2 - DEFINING CLASSES 62public class Date {
private void writeOutput(){
[Link]("The day is: " +day + ", the month is: " + month + ", the year is: " +year); }
}
initialized
to usable values. This could be accomplished by: 1. Initializing instance
•Constructors
A signature consists of the name of a method together with its parameter list
Dr. Abed EL Safadi
Method Signature
CHAPTER 2 - DEFINING CLASSES 65
In Java, two or more methods may have the same name inside the same classif
they
differ in their signatures different number of parameters
CHAPTER 2 - DEFINING
CLASSES 67
Overloading by changing the number of parameters
Overloading by changing the type of parameters
DEFINING CLASSES 68
oSuppose, you have to perform the addition of given numbers but there can be any
accomplish the task, you can create two methods sum2num(int, int) and
sum3num(int,
they differ by name oThe better way to accomplish this task is by overloading methods
o And, depending upon the argument passed, one of the overloaded methods is called o This
helps to increase the readability of the program
Overloading Example 1
Overloading Example 2
initialized
to usable values. This could be accomplished by: 1. Initializing instance
ClassName(anyParameters){
}
The name of the constructor and its parenthesized list of arguments (if any) must follow
thenewDr. Abed EL Safadi
operator CHAPTER 2 - DEFINING CLASSES 75
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
Dr. Abed EL Safadi
Initialize Instance Variables Using
Constructors CHAPTER 2 - DEFINING CLASSES 76public
class Demo {
public static void main(String[] args) {
}
}
Dr. Abed EL Safadi
Constructors Types
CHAPTER 2 -
DEFINING CLASSES 77Constructors Types
Default
constructor Non-default
constructor
No arguments
With arguments
constructor
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
If
• Default values can also be the values specified when declaring instance variables
you add no constructor definitions to your class, then Java automatically creates the
default
constructorCHAPTER 2 - DEFINING CLASSES 78public Date(){
Default Constructor
public Date(){
year = 0;
month = null;
}
day = 0;
}
To initialize instance variables to specific values, you need to define your
[Link] = month;
[Link] = day;
Multiple constructors can be created – Constructor overloading
Dr. Abed EL Safadi
Non-Default Constructor
year, String month, int day){
[Link] = year;
constructor
public Date(int
CHAPTER 2 - DEFINING CLASSES 79
public Date(int y, int d){ year = y;
day = d;
}
}
Default
Constructors - Example [Link] = month;
[Link] = day;
Dr. Abed EL Safadi