0% found this document useful (0 votes)
2 views91 pages

Chapter 2 - Defining Classes

Chapter 2 focuses on defining classes in Java, emphasizing the Object-Oriented Programming (OOP) approach which organizes programs into classes and objects. It covers class definitions, instance variables, methods, object creation, and the importance of encapsulation and the toString() method. The chapter also distinguishes between local, instance, and static variables, providing examples for clarity.

Uploaded by

101220462
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views91 pages

Chapter 2 - Defining Classes

Chapter 2 focuses on defining classes in Java, emphasizing the Object-Oriented Programming (OOP) approach which organizes programs into classes and objects. It covers class definitions, instance variables, methods, object creation, and the importance of encapsulation and the toString() method. The chapter also distinguishes between local, instance, and static variables, providing examples for clarity.

Uploaded by

101220462
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter 2

Defining Classes

INSTRUCTOR: DR. RAYANE EL SIBAI


Dr. Rayane El Sibai

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

CHAPTER 2 - DEFINING CLASSES 2


Part 2.1 •Classes and Objects
• OOP Approach
• Class Definition
• Variables in Java
• toString Method

•Information Hiding and Encapsulation


•Overloading
•Constructors

CHAPTER 2 - DEFINING CLASSES 3


Dr. Rayane El Sibai

Reminder: What You Know


There are different approaches to writing computer programs, they all involve
decomposing your programs into parts
What is different between the approaches is how the decomposition occurs - criteria
used for breaking things down
Two approaches to decomposition have been presented to you so far:
oProcedure-Oriented Programming (POP)
oObject-Oriented Programming (OOP)

CHAPTER 2 - DEFINING CLASSES 4


Dr. Rayane El Sibai

POP Approach - Example


Break down the program by what it does (described with actions/verbs)
PowerPoint

Filing Editing … Helping

Creating new Opening a Saving a … Exiting


document document document program

CHAPTER 2 - DEFINING CLASSES 5


Dr. Rayane El Sibai

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

OOP Approach – Example


A class is like a blueprint of a house: you can build more than one house from a
blueprint
In the same way, you can create more objects from a class

CHAPTER 2 - DEFINING CLASSES 7


Dr. Rayane El Sibai

OOP Approach – Example


A class is a prototype that defines the variables and the methods (actions) common to
all 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.

CHAPTER 2 - DEFINING CLASSES 8


Dr. Rayane El Sibai

OOP Approach – Example


Attributes values can be added, changed, removed, some can also be read-only
color is a an attribute of the house, red and green are attributes values

CHAPTER 2 - DEFINING CLASSES 9


Dr. Rayane El Sibai

OOP Approach – Example


Methods are actions that are performed on objects
Changing the color of the house is a method performed on the house object

CHAPTER 2 - DEFINING CLASSES 10


Dr. Rayane El Sibai

OOP Approach – Zoo Example (1/5)

Break down the program into entities (classes/objects - described with nouns)

Zoo

Animal Building

Visitor
Lions
Tigers Staff
Admin
Dogs
Animal care

CHAPTER 2 - DEFINING CLASSES 11


Dr. Rayane El Sibai

OOP Approach – Zoo Example (2/5)

Each class includes descriptive data (attributes)


Example for the class Animal: color, age, breed, size, etc.

CHAPTER 2 - DEFINING CLASSES 12


Dr. Rayane El Sibai

OOP Approach – Zoo Example (3/5)

Each class has an associated set of actions


Example for the class Animal: sleeping, eating, running, siting

CHAPTER 2 - DEFINING CLASSES 13


Dr. Rayane El Sibai

OOP Approach – Zoo Example (4/5)

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

CHAPTER 2 - DEFINING CLASSES 14


Dr. Rayane El Sibai

OOP Approach – Zoo Example (5/5)

Now, for different values of the attributes (breed size, age, and color) in the class, we will
get different animals objects

CHAPTER 2 - DEFINING CLASSES 15


Dr. Rayane El Sibai

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()

CHAPTER 2 - DEFINING CLASSES 16


Dr. Rayane El Sibai

Class Definition Syntax

CHAPTER 2 - DEFINING CLASSES 17


Dr. Rayane El Sibai

Class Definition - Example


public class Date {

public int year;


public String month;
public int day;

public void writeOutput(){


[Link]("The day is: " +day + ", the month is: " + month + ", the year is: " +year);
}

CHAPTER 2 - DEFINING CLASSES 18


Dr. Rayane El Sibai

Instance Variables
Instance variables (attributes) can be defined as follows:

String instanceVar1;
int instanceVar2;

Example
int year;
String month;
int day;

CHAPTER 2 - DEFINING CLASSES 19


Dr. Rayane El Sibai

Methods
Method definitions are divided into two parts: a heading and a method body:

void myMethod() Heading


{
//code to perform some action Body
}

CHAPTER 2 - DEFINING CLASSES 20


Dr. Rayane El Sibai

Object Creation – Step 1


An object of a class is named or declared by a variable of the class type:

ClassName classVar;

Example
Date date1, date2;

CHAPTER 2 - DEFINING CLASSES 21


Dr. Rayane El Sibai

Object Creation – Step 2 (1/2)

The new operator must be used to create the object and associate it with its variable
name:

classVar = new ClassName();

Example
date1 = new Date ();
date2 = new Date ();

CHAPTER 2 - DEFINING CLASSES 22


Dr. Rayane El Sibai

Object Creation – Step 2 (2/2)

These can be combined as follows:

ClassName classVar = new ClassName();

Example
Date date1 = new Date ();
Date date2 = new Date ();

CHAPTER 2 - DEFINING CLASSES 23


Dr. Rayane El Sibai

Object Creation - Summary

CHAPTER 2 - DEFINING CLASSES 24


Dr. Rayane El Sibai

The Calling Object (1/4)

Instance variables can be defined as in the In order to refer to a particular instance


following two examples: variable, preface it with its object name as
follows:

String instanceVar1; objectName.instanceVar1


int instanceVar2; objectName.instanceVar2

Example Example
int year; [Link] = “July”;
String month; [Link] = 4;
int day; [Link] = 1776;

CHAPTER 2 - DEFINING CLASSES 25


Dr. Rayane El Sibai

The Calling Object (2/4)

Methods are invoked using the name of the calling object and the method name as
follows:

[Link]();

Example

[Link]();

CHAPTER 2 - DEFINING CLASSES 26


Dr. Rayane El Sibai

The Calling Object (3/4)

In the method definition, all instance variables are understood to have a hidden
<calling object>. in front of them

public void writeOutput(){


[Link]("The day is: " +day + ", the month is: " + month + ", the year is: " +year);
}

public void writeOutput(){


[Link]("The day is: " + <calling object>.day + ", the month is: " + <calling object>.month + ",
the year is: " + <calling object>.year);
}

CHAPTER 2 - DEFINING CLASSES 27


Dr. Rayane El Sibai

The Calling Object (4/4)

Invoking a method is equivalent to executing the method body:

[Link](); is equivalent to:

[Link]("The day is: " + [Link] + ", the month is: " + [Link] + ",
the year is: " + [Link]);

CHAPTER 2 - DEFINING CLASSES 28


public class Demo {
public static void main(String[] args) { The Calling Object -
Date date1, date2;
date1 = new Date(); Example
date2 = new Date();

[Link] = 3;
[Link] = "December";
[Link] = 2022;

[Link] = 10;
[Link] = "February";
[Link] = 2023;

[Link]("Date1 is: ");


[Link]();
[Link]("Date2 is: ");
[Link]();
}
}

CHAPTER 2 - DEFINING CLASSES 29


Dr. Rayane El Sibai

The this Parameter


The this keyword in Java is used to refer to the current object. It is a kind of hidden parameter
myInstanceVariable means and is interchangeable with [Link]

public void writeOutput(){


[Link]("The day is: " +day + ", the month is: " + month + ", the year is: " +year);
}

public void writeOutput(){


[Link]("The day is: " + [Link] + ", the month is: " + [Link] + ", the year is: " + [Link]);
}

CHAPTER 2 - DEFINING CLASSES 30


Dr. Rayane El Sibai

When to use the this Parameter?


In the method definition, if an explicit name for the calling object is needed, the
keyword this can be used
this must be used if a parameter or other local variable with the same name as the
instance variables is used in the method. Otherwise, all instances of the variable name
will be interpreted as local

CHAPTER 2 - DEFINING CLASSES 31


Dr. Rayane El Sibai

The this Parameter - Example


public void changeDate (int day, String month, int year){
day = day;
month = month;
year = year;
}

public void changeDate (int day, String month, int year){


[Link] = day;
[Link] = month;
[Link] = year;
}

CHAPTER 2 - DEFINING CLASSES 32


Example of a
predefined class

The Scanner Class

CHAPTER 2 - DEFINING CLASSES 33


Dr. Rayane El Sibai

Variables in Java (1/4)

There are basically three types of variables in Java:


oLocal variables
oInstance variables
oStatic variables / Class variables

Some programming languages include another kind of variable called a global variable -
The Java language does NOT have global variables

CHAPTER 2 - DEFINING CLASSES 34


Dr. Rayane El Sibai

Variables in Java (2/4)

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

CHAPTER 2 - DEFINING CLASSES 35


Dr. Rayane El Sibai

Variables in Java (3/4)

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

CHAPTER 2 - DEFINING CLASSES 36


Dr. Rayane El Sibai

Variables in Java (4/4)

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

CHAPTER 2 - DEFINING CLASSES 37


Dr. Rayane El Sibai

Initialize Instance Variables


In order to put the object into a usable state, its instance variables should be initialized
to usable values. This could be accomplished by:
1. Initializing instance variables when you declare them in a class definition - at the
time of declaration
2. Calling the various set methods
3. Initializing using constructor

CHAPTER 2 - DEFINING CLASSES 38


Dr. Rayane El Sibai

Initialize Instance Variables at Declaration Time


Initializing instance variables when you declare them in a class definition - at the time of
declaration

public class Date {

public int year = 2022;


public String month = “January”;
public int day = 3;

CHAPTER 2 - DEFINING CLASSES 39


Dr. Rayane El Sibai

The Method toString (1/3)

Java expects certain methods to be in almost all classes


One of these methods is called toString(), of type String
The purpose of the toString() (an in-built method) is to return a String value that
represents the data in the object

CHAPTER 2 - DEFINING CLASSES 40


Dr. Rayane El Sibai

The Method toString (2/3)

[Link] automatically invokes toString() if you do not include it


If you print any object, Java compiler internally invokes the toString() method on the object

[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)

CHAPTER 2 - DEFINING CLASSES 41


Dr. Rayane El Sibai

The Method toString (3/3)

To print meaningful values, you need to override the method


Redefining the toString() method returns the desired output, it can be the state of an
object etc., depending on your implementation

public String toString(){


return "The day is: " + day + ", the month is: " + month + ", the year is: " + year;
}

CHAPTER 2 - DEFINING CLASSES 42


Part 2.2 •Classes and Objects
•Information Hiding and Encapsulation
• Encapsulation Concept
• Implementing Encapsulation
• public/private Modifiers – Instance Variables & Methods
• Accessor and Mutator Methods

•Overloading
•Constructors

CHAPTER 2 - DEFINING CLASSES 43


Dr. Rayane El Sibai

Encapsulation Concept (1/2)

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

CHAPTER 2 - DEFINING CLASSES 44


Dr. Rayane El Sibai

Encapsulation Concept (2/2)

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

CHAPTER 2 - DEFINING CLASSES 45


Dr. Rayane El Sibai

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

CHAPTER 2 - DEFINING CLASSES 46


Dr. Rayane El Sibai

public/private Modifiers – Instance Variables


The modifier public means that there are no restrictions on where an instance variable
or method can be used
The modifier private means that an instance variable or method cannot be accessed by
name outside of the class: a private field can only be accessed through code the same
class defines

CHAPTER 2 - DEFINING CLASSES 47


Dr. Rayane El Sibai

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;

}
}

CHAPTER 2 - DEFINING CLASSES 48


Dr. Rayane El Sibai

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]);
}
}

CHAPTER 2 - DEFINING CLASSES 49


Dr. Rayane El Sibai

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;

}
}

CHAPTER 2 - DEFINING CLASSES 50


Dr. Rayane El Sibai

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]);
}
}

CHAPTER 2 - DEFINING CLASSES 51


Dr. Rayane El Sibai

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

CHAPTER 2 - DEFINING CLASSES 52


Dr. Rayane El Sibai

Accessor and Mutator Methods


public methods are used to access the private data members from outside of the class

get data set data


(accessor (mutator
method) method)

public public public


method method method

private
data

CHAPTER 2 - DEFINING CLASSES 53


Dr. Rayane El Sibai

Accessor (Getter) Methods


Accessor (getter) methods allow the programmer to obtain the value of an object's
instance variables
The data can be accessed but not changed
By convention, the name of an accessor method is: getFieldName()

Example
getDay(), getMonth(), getYear()

CHAPTER 2 - DEFINING CLASSES 54


Dr. Rayane El Sibai

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; } }

public int getDay() {


return day; }
}

CHAPTER 2 - DEFINING CLASSES 55


Dr. Rayane El Sibai

Mutator (Setter) Methods


Mutator (setter) methods allow the programmer to change the value of an object's
instance variables in a controlled manner
By convention, the name of a mutator method is: setFieldName()
Example
setDay(), setMonth(), setYear()

CHAPTER 2 - DEFINING CLASSES 56


Dr. Rayane El Sibai

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; } }

public void setDay(int day) {


[Link] = day; }
}

CHAPTER 2 - DEFINING CLASSES 57


Dr. Rayane El Sibai

accessor/mutator vs public modifier

Are the accessor and mutator methods equivalent to making the instance variables
public?

CHAPTER 2 - DEFINING CLASSES 58


Dr. Rayane El Sibai

accessor/mutator vs public modifier


Input validation: public class Date {
…..
We might need to add some check(s) for a field private int day;
(change the value of a field if and only if a
condition(s) is/are satisfied) public void setDay(int day) {
if(day > 0 && day <= 31){
If we want to add additional check(s) for a field, [Link] = day;
we will just have to change the setter method of }
that field else{
This wouldn't be possible if the field was public [Link](“Your value is wrong!);
day = 0;
}
}

public int getDay() {…}


}

CHAPTER 2 - DEFINING CLASSES 59


Dr. Rayane El Sibai

accessor/mutator vs public modifier


Making a field read-only public class Date {
…..
To restrict the access of a field to read-
private int day;
only (a field can be read but not
written), the field can be accessed with
public int getDay() {
a getter only (without a setter)
return day;
This wouldn't be possible if the field was }
public
public void setDay(int day) {…}
}

CHAPTER 2 - DEFINING CLASSES 60


Dr. Rayane El Sibai

public/private Modifiers – Methods


The modifiers public and private before a method definition have a similar meaning
If the method is labeled public, there are no restrictions on its usage
If the method is labeled private, the method can only be used in the definition of another
method of the same class
Usually, methods are private if they are used as helping methods for other methods in the class

CHAPTER 2 - DEFINING CLASSES 61


Dr. Rayane El Sibai

Example
public class Date {

private void writeOutput(){


[Link]("The day is: " +day + ", the month is: " + month + ", the year is: " +year);
}
}

public class Demo {


public static void main(String[] args) {

Date date1 = new Date();


[Link]();
}
}

CHAPTER 2 - DEFINING CLASSES 62


Dr. Rayane El Sibai

Initialize Instance Variables


In order to put the object into a usable state, its instance variables should be initialized
to usable values. This could be accomplished by:
1. Initializing instance variables when you declare them in a class definition - at the
time of declaration
2. Calling the various set methods
3. Initializing using constructor

CHAPTER 2 - DEFINING CLASSES 63


Part 2.3 •Classes and Objects
•Information Hiding and Encapsulation
•Overloading
• Method Signature
• Overloading Concept

•Constructors

CHAPTER 2 - DEFINING CLASSES 64


Dr. Rayane El Sibai

Method Signature
A signature consists of the name of a method together with its parameter list

CHAPTER 2 - DEFINING CLASSES 65


Dr. Rayane El Sibai

Overloading Concept (1/3)

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

CHAPTER 2 - DEFINING CLASSES 66


Dr. Rayane El Sibai

Overloading Concept (2/3)

Overloading by changing the number of parameters

Overloading by changing the type of parameters

Overloading by changing the order of parameters

CHAPTER 2 - DEFINING CLASSES 67


Dr. Rayane El Sibai

Overloading Concept (3/3)

You can’t overload based on the type returned!!!!!!!!

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

CHAPTER 2 - DEFINING CLASSES 68


Dr. Rayane El Sibai

Why Method Overloading?


oSuppose, you have to perform the addition of given numbers but there can be any number of
arguments (let’s say either 2 or 3 arguments for simplicity)
oIn order to accomplish the task, you can create two methods sum2num(int, int) and
sum3num(int, int, int) for two and three parameters respectively
oHowever, other programmers, as well as you in the future may get confused as the behavior of
both methods are the same but 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

CHAPTER 2 - DEFINING CLASSES 69


Dr. Rayane El Sibai

Overloading Example 1
Overloading by changing the number of parameters

Output

CHAPTER 2 - DEFINING CLASSES 70


Dr. Rayane El Sibai

Overloading Example 2
Overloading by changing the type of parameters

Output

CHAPTER 2 - DEFINING CLASSES 71


Part 2.4 •Classes and Objects
•Information Hiding and Encapsulation
•Overloading
•Constructors
• What is a Constructor?
• Default Constructor
• Non-Default Constructor
• Calling Constructor
• this constructor
• Representing Classes

CHAPTER 2 - DEFINING CLASSES 72


Dr. Rayane El Sibai

Initialize Instance Variables


In order to put the object into a usable state, its instance variables should be initialized
to usable values. This could be accomplished by:
1. Initializing instance variables when you declare them in a class definition - at the
time of declaration
2. Calling the various set methods
3. Initializing using constructor

CHAPTER 2 - DEFINING CLASSES 73


Dr. Rayane El Sibai

Initialize Instance Variables Using Constructors


Java provides another method for initializing objects: Constructors
A constructor is a special kind of method that is designed to initialize the instance variables for
an object

ClassName(anyParameters){
//code that initializes instance variables
}

◦ A constructor must have the same name as the class


◦ A constructor has no type returned, not even void
◦ Constructors are typically overloaded: A class can have multiple constructors

CHAPTER 2 - DEFINING CLASSES 74


Dr. Rayane El Sibai

Initialize Instance Variables Using Constructors


A constructor is called when an object of the class is created using the new operator

ClassName objectName = new ClassName(anyArgs);

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

CHAPTER 2 - DEFINING CLASSES 75


Dr. Rayane El Sibai

Initialize Instance Variables Using Constructors


public class Demo {
public static void main(String[] args) {

Date date1 = new Date();

}
}

CHAPTER 2 - DEFINING CLASSES 76


Dr. Rayane El Sibai

Constructors Types
Constructors Types
Default
Non-default constructor
constructor

No arguments With arguments


constructor constructor

CHAPTER 2 - DEFINING CLASSES 77


Dr. Rayane El Sibai

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;
}

CHAPTER 2 - DEFINING CLASSES 78


Dr. Rayane El Sibai

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;
}

Multiple constructors can be created – Constructor overloading

CHAPTER 2 - DEFINING CLASSES 79


Dr. Rayane El Sibai

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;
} }

Of course, the default constructor and the no-arguments


constructor can’t both exist in the class Date since they have
the same signature!

CHAPTER 2 - DEFINING CLASSES 80


Dr. Rayane El Sibai

Calling Constructor - Example


public class Demo {
public static void main(String[] args) {

Date date1, date2, date3;


date1 = new Date();
date2 = new Date(2021, “August”, 21);
date3 = new Date(2020, 4);

}
}

CHAPTER 2 - DEFINING CLASSES 81


Dr. Rayane El Sibai

Calling Constructor – Additional Notes


If you include one or more constructors that each takes one or more arguments, but you do not
include a no-argument constructor in your class definition, then, Java will not automatically
create the default constructor, and the following will be illegal:

public class Date { public class Demo {


private int year; public static void main(String[] args) {
private String month;
private int day; Date date1 = new Date();

public Date(int y, int d){ Date date2 = new Date(2020, 11);


year = y;
day = d; }
}
} }

CHAPTER 2 - DEFINING CLASSES 82


Dr. Rayane El Sibai

Calling Constructor Multiple Times


If a constructor is invoked again (using new), the first object is discarded and an entirely
new object is created

public class Demo {


public static void main(String[] args) {

Date date1;
date1 = new Date();
date1 = new Date(2021, “August”, 21);

}
}

CHAPTER 2 - DEFINING CLASSES 83


Dr. Rayane El Sibai
Change Instance Variables Values with
Constructors
You cannot call a constructor for an object after it is created
So, if you need to change the values of instance variables of the object, use setter
methods instead
public class Demo {
public static void main(String[] args) {

Date date1;
date1 = new Date();
[Link](2023, “December”, 20);

}
}

CHAPTER 2 - DEFINING CLASSES 84


Dr. Rayane El Sibai

Invoke Another Method in a Constructor


It is legal to invoke another method within the definition of a constructor. For example,
mutator methods can be used to set the values of the instance variables
public Date(int year, String month, int day){
[Link](“It is a date”);
setYear(year);
setMonth(month);
setDay(day);
}

It is even possible for one constructor to invoke another (See Chapter 4 - Inheritance)

CHAPTER 2 - DEFINING CLASSES 85


Dr. Rayane El Sibai

The this Constructor


Within the definition of a constructor for a class, this can be used as a name for
invoking another constructor in the same class
We can use this only inside constructor and nowhere else, not even inside methods
Any call to the constructor this must always be the first action taken in a constructor
definition

CHAPTER 2 - DEFINING CLASSES 86


Dr. Rayane El Sibai

The this Constructor - Example


public class Date {
private int year; public Date(int day, String month){
private String month; this(); //[Link] = 2023;
private int day; [Link] = day;
[Link] = month;
public Date(){ }
[Link] = 2023; }
}

CHAPTER 2 - DEFINING CLASSES 87


Dr. Rayane El Sibai

The this Constructor - Example


public class Date {
private int year; public Date(int year, int day, String month){
private String month; this(year, day); //[Link] = year; //[Link] = day;
private int day; [Link] = month;
}
public Date(int year, int day){ }
[Link] = year;
[Link] = day;
}

CHAPTER 2 - DEFINING CLASSES 88


Dr. Rayane El Sibai

Note: final Variables


final variables: when a variable is declared as final, its value cannot be changed once it has been initialized

final int BIRTH_YEAR;

A final variable must be always initialized, either at the declaration time, or in the constructor of the class

public class Person{


final int BIRTH_YEAR = 2023;
final int BIRTH_YEAR ;

public Person(){
BIRTH_YEAR = 2023;
}
}

CHAPTER 2 - DEFINING CLASSES 89


Dr. Rayane El Sibai

Representing Classes – The class Date


Date
- year: int
- month: String
- day: int
+ Date()
+ Date(int year, String month, int day)
+ Date(int y, int d)
+ getYear(): int
+ getMonth(): String
+ getDay(): int
+ setYear(int year): void
+ setMonth(String month): void
+ setDay(int day): void
+ setDate(int year, String month, int day): void
+ writeOutput(): void
+ toString(): String

CHAPTER 2 - DEFINING CLASSES 90


Dr. Rayane El Sibai

Representing Classes – The class Date


Date
- year: int
- month: String
- day: int
+ Date()
+ Date(int year, int month, int day)
+ Date(int y, int d)
+ monthString(int month): String
+ getYear(): int
+ getMonth(): String
+ getDay(): int
+ setYear(int year): void
+ setMonth(int month): void
+ setDay(int day): void
+ setDate(int year, int month, int day): void
+ writeOutput(): void
+ toString(): String

CHAPTER 2 - DEFINING CLASSES 91

You might also like