0% found this document useful (0 votes)
4 views70 pages

Chapter 2 - Defining Classes

Chapter 2 covers the definition of classes in Java, focusing on the Object-Oriented Programming (OOP) approach, which emphasizes the use of classes and objects. Key topics include class definitions, instance variables, methods, encapsulation, and the importance of the toString() method for object representation. The chapter also discusses the creation and manipulation of objects, highlighting the use of access modifiers for data hiding and encapsulation.

Uploaded by

jadelhajj31
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)
4 views70 pages

Chapter 2 - Defining Classes

Chapter 2 covers the definition of classes in Java, focusing on the Object-Oriented Programming (OOP) approach, which emphasizes the use of classes and objects. Key topics include class definitions, instance variables, methods, encapsulation, and the importance of the toString() method for object representation. The chapter also discusses the creation and manipulation of objects, highlighting the use of access modifiers for data hiding and encapsulation.

Uploaded by

jadelhajj31
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. ABED EL SAFADI


The content of this presentation is prepared based on: oABSOLUTE JAVA™ 6th
Edition Global Edition oPowerPoint Lecture Slides for Absolute Java, Global Edition oWebsites

notesCHAPTER 2 - DEFINING CLASSES 2

Dr. Abed EL Safadi

REFERENCES CHAPTER 2 - DEFINING CLASSES 3

Part 2.1 •Classes and Objects • OOP Approach


• Class Definition
• Variables in Java
• toString Method

•Information Hiding and Encapsulation


•Overloading
•Constructors
There are different approaches to writing computer programs, they all

involve What is different between the


decomposing your programs into parts

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)
Dr. Abed EL Safadi

Reminder: What You Know


CHAPTER 2 - DEFINING CLASSES 4

POP Approach - Example


Dr. Abed EL Safadi

CHAPTER 2 - DEFINING CLASSES 5Filing Editing … Helping


Break down the program by what it does (described with actions/verbs)
PowerPoint
Creating new
Opening a
Saving a
…Exiting
document
document
document program
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
Dr. Abed EL Safadi

OOP Approach
CHAPTER 2 - DEFINING CLASSES 64-6

OOP Approach – Example


A class is like a blueprint of a house: you can build more
CHAPTER 2 - DEFINING CLASSES 7
than one house from a
blueprint
In the same way, you can create more objects from a class Dr. Abed EL Safadi

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.
Dr. Abed EL Safadi

CHAPTER 2 - DEFINING CLASSES 8


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
Dr. Abed EL Safadi

CHAPTER 2 - DEFINING CLASSES 9


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
Dr. Abed EL Safadi

CHAPTER 2 - DEFINING CLASSES 10

OOP Approach – Zoo Example


(1/5)
Break down the program into entities (classes/objects - described with nouns)
Dr. Abed EL Safadi

CHAPTER 2 - DEFINING CLASSES 11Zoo


Animal Building

Visitor
Lions
Staff
Tigers
Admin Animal care
Dogs

OOP Approach – Zoo Example


(2/5) Each class includes descriptive data (attributes)

Example for the class Animal: color, age, breed, size, etc.
Dr. Abed EL Safadi
CHAPTER 2 - DEFINING CLASSES 12

OOP Approach – Zoo Example


(3/5) Each class has an associated set of actions

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


Dr. Abed EL Safadi
CHAPTER 2 - DEFINING CLASSES 13

OOP Approach – Zoo Example


(4/5) Now, we can design the ZOO program using the OOP approach: Data
members: size, age, color, and breed
Methods: eat, sleep, sit, and run
Dr. Abed EL Safadi
Class: Animal
CHAPTER 2 - DEFINING CLASSES

14
Now, for different values of the attributes (

breed size, age, and

color) in the class, we will


get different animals objectsCHAPTER 2 - DEFINING CLASSES

OOP Approach – Zoo Example


15

(5/5)Dr. Abed EL Safadi


A class definition specifies the data items and methods that all of its objects will
[Link] data items and methods are called members of the object Data
Instance
items are called fields, instance variables, data members, or attributes

variables declarations and methods definitions can be placed in any order


within

the class definitionCHAPTER 2 - DEFINING CLASSES 16


Dr. Abed EL Safadi

Class Definition
Dr. Abed EL Safadi

Class Definition Syntax


CHAPTER 2 -
DEFINING CLASSES 17

Class Definition - Example


Dr. Abed EL Safadi

CHAPTER 2 - DEFINING CLASSES 18


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

}
Instance variables (attributes) can be defined as follows: String instanceVar1;
int instanceVar2;
int year;
String month;

Dr. Abed EL Safadi


int day;CHAPTER 2 - DEFINING CLASSES 19

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
}

Object Creation – Step 1 An object of a


class is named or declared by a variable of the class type: ClassName classVar;
Dr. Abed EL Safadi

Date date1, date2;CHAPTER 2 - DEFINING CLASSES 21Example

Object Creation – Step 2 (1/2)


The new operator must be used to create the object and associate it with its
name:
variable classVar = new ClassName();

Dr. Abed EL Safadi

date2 = new Date ();CHAPTER 2 - DEFINING CLASSES 22


Example
date1 = new Date ();

Object Creation – Step 2 (2/2) These can

be combined as follows:
ClassName classVar = new ClassName();
Dr. Abed EL Safadi

Date date2 = new Date ();CHAPTER 2 - DEFINING CLASSES 23


Example
Date date1 = new Date ();
Dr. Abed EL Safadi

Object Creation - Summary


CHAPTER 2 -
DEFINING CLASSES 24
Instance variables can be defined as in the
In order to refer to a particular instancevariable, preface it with its object name
int day;
as
follows:
following two examples:
String instanceVar1;
int instanceVar2;CHAPTER 2 - DEFINING CLASSES 25Example
int year; String month;
[Link] = “July”;
[Link] = 4;
[Link] = 1776;
Dr. Abed EL Safadi

The Calling Object (1/4)

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)

CHAPTER 2 - DEFINING CLASSES 26Example


[Link]();

[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

Calling Object (3/4)


Dr. Abed EL Safadi
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);
}
Dr. Abed EL Safadi

The Calling Object (4/4)


CHAPTER 2 - DEFINING CLASSES 28
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]);
public class Demo { date2 = new Date(); [Link] = 3;

The Calling Object CHAPTER 2 - DEFINING CLASSES

-
public static void main(String[] args) {
29
Date date1, date2;
date1 = new Date();

Example
[Link] = "December"; [Link]
= 2022;
[Link] = 10;
[Link] = "February"; [Link]
= 2023;

[Link]("Date1 is: ");


[Link]();
[Link]("Date2 is: ");
[Link]();
}
}
The this keyword in Java is used to refer to the current object. It is a kind of

hiddenmyInstanceVariable means and is interchangeable with

[Link] 2 - DEFINING CLASSES 30public void writeOutput(){


[Link]("The day is: " + [Link] + ", the month is: " + [Link] + ", the year is: " +
[Link]);
Dr. Abed EL Safadi

The this Parameter


parameter

public void writeOutput(){


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

}
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

Variables in Java (1/4)


CHAPTER 2 - DEFINING CLASSES 34
There are basically three types of variables in Java:
oLocal variables
oInstance variables
oStatic variables / Class 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
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

Variables in Java (3/4)


CHAPTER 2 - DEFINING CLASSES 36
Static variables
oAn static variable is declared inside a class but outside of any method or
blockoAn static variable is accessible throughout the class oStatic variables only
have one single copy for the entire class oUsed for storing constantsCHAPTER 2 -
DEFINING CLASSES 37 Variables in Java (4/4)Dr. Abed EL

Safadi
In order to put the object into a usable state, its instance variables should be

initialized Initializing instance


to usable values. This could be accomplished by: 1.

variables when you declare them in a class definition - at the


time of declaration 2.

Calling the various set methods


3. Initializing using constructorCHAPTER 2 - DEFINING CLASSES 38
Dr. Abed EL Safadi

Initialize Instance Variables


Initializing instance variables when you declare them in a class definition - at the
time of
Dr. Abed EL Safadi

Initialize Instance Variables at Declaration


Timedeclaration public class Date {
CHAPTER 2 - DEFINING CLASSES 39
public int year = 2022;
public String month = “January”;
public int day = 3;

}
Java expects certain methods to be in almost all classes
The purpose of the
One of these methods is called toString(), of type String

toString() (an in-built method) is to return a String value that


represents the data

in the objectCHAPTER 2 - DEFINING CLASSES 40


Dr. Abed EL Safadi

The Method toString (1/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 objectCHAPTER 2 - DEFINING CLASSES [Link](date1);

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

To print meaningful values, you need to override the method


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

The Method toString (3/3) CHAPTER 2 - DEFINING CLASSES


42public String toString(){
return "The day is: " + day + ", the month is: " + month + ", the year is: " + year;}
• public/private Modifiers – Instance Variables & Methods
CHAPTER 2 - DEFINING CLASSES 43

Part 2.2 •Classes and Objects


•Information Hiding and Encapsulation
• Encapsulation Concept
• Implementing Encapsulation

• Accessor and Mutator Methods

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

these attributes and


methods of a date named Date.

Dr. Abed EL Safadi

Encapsulation Concept (1/2)


CHAPTER 2 - DEFINING CLASSES 44

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

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
Dr. Abed EL Safadi

Encapsulation Concept (2/2)


CHAPTER 2 - DEFINING CLASSES 45

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

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 fieldsCHAPTER 2 - DEFINING

CLASSES 46Dr. Abed EL Safadi

public/private Modifiers – Instance


means that there are no
VariablesThe modifier public

restrictions on where an instance variable


or method
can be used The modifier private means that an instance variable or method
field can only be
cannot be accessedbyname outside of the class: a private

accessed through code the same


class definesCHAPTER 2 - DEFINING CLASSES 47Dr. Abed

EL Safadi
Dr. Abed EL Safadi

Example 1

CHAPTER 2 - DEFINING CLASSES 48public class Date {


public class Demo {
public static void main(String[] args) {
public int year;
public String month; public int
day; }
[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 2

CHAPTER 2 - DEFINING CLASSES 49public class Demo {


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

}
}
Dr. Abed EL Safadi

Example 3

CHAPTER 2 - DEFINING CLASSES 50public class Date {


public class Demo {
public static void main(String[] args) {
private int year;
private String month; private int
day;

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

CHAPTER 2 - DEFINING CLASSES 51public class Demo {


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

date1 = new Date();

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

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

Accessor and Mutator Methods

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

By convention, the name of an accessor method is: getFieldName()


Dr. Abed EL Safadi

Accessor (Getter) Methods getDay(),


getMonth(), getYear()CHAPTER 2 - DEFINING CLASSES 54
Example

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

CHAPTER 2 - DEFINING CLASSES 55public class Date { public class Demo {

private int year; private String month; private


int day; Date date1;
public static void main(String[] args) { date1 = new Date();
public int getYear() {
return year; }

public String getMonth() {


}
return month; }
}

public int getDay() {


return day; }
}
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() setDay(), setMonth(), setYear()CHAPTER 2 -

DEFINING CLASSES 56

Dr. Abed EL Safadi

Mutator (Setter) Methods Example

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

private String month; private int Date();


day;

Date date1; date1 = new


public void setYear(int year) {
[Link](3);
[Link] = year; } [Link](2022);
[Link](“January”);
public void setMonth(String month) {
}
}

public void setDay(int day) {

}
Dr. Abed EL Safadi

accessor/mutator vs public modifier CHAPTER 2 -


DEFINING CLASSES 58
Are the accessor and mutator methods equivalent to making the
instancevariables public?
Input validation:
We might need to add some check(s) for a field (change the value of a field if and only if
a condition(s) is/are satisfied)
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
This wouldn't be possible if the field was public
Dr. Abed EL Safadi

accessor/mutator vs public modifier


public class Date { …..
CHAPTER 2 - DEFINING CLASSES 59 private int
day;
public void setDay(int day) {
if(day > 0 && day <= 31){

}
else{
[Link](“Your value is wrong!);
day = 0;
}
}

public int getDay() {…}


}
Making a field read-only
To restrict the access of a field to read
only (a field can be read but not
written), the field can be accessed with
a getter only (without a setter)
This wouldn't be possible if the field was
Dr. Abed EL Safadi

accessor/mutator vs public modifier


public class Date { …..
publicCHAPTER 2 - DEFINING CLASSES 60 private int day;
public int getDay() {
return day;
}
public void setDay(int day) {…}
}
Usually, methods are private if they are used as helping methods for other methods in

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

private, the method can only be used in the definition of another


method of the same

class Dr. Abed EL Safadi


Dr. Abed EL Safadi

Example
CHAPTER 2 - DEFINING CLASSES 62public 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]();
}
}
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 thetime of declaration

2. Calling the various set methods


3. Initializing using constructorCHAPTER 2 - DEFINING CLASSES 63
Dr. Abed EL Safadi

Initialize Instance Variables CHAPTER 2 - DEFINING CLASSES 64

Part 2.3 •Classes and Objects •Information Hiding and


Encapsulation
•Overloading
• Method Signature
• Overloading Concept

•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

 different types of parameters


 order of parameters
These methods are called overloaded methods and this feature is called method
Dr. Abed EL Safadi
Overloading Concept (1/3) overloadingCHAPTER 2 -
DEFINING CLASSES 66
Dr. Abed EL Safadi

Overloading Concept (2/3)

CHAPTER 2 - DEFINING
CLASSES 67
Overloading by changing the number of parameters
Overloading by changing the type of parameters

Overloading by changing the order of parameters


oThe return types of the previous methods are the same oIt is because method
oOverloaded methods may have
overloading is not associated with return types

the same or different return types, but they must


differ in parametersCHAPTER 2 -

DEFINING CLASSES 68

Dr. Abed EL Safadi


Overloading Concept (3/3) You can’t overload

based on the type returned!!!!!!!!

oSuppose, you have to perform the addition of given numbers but there can be any

number of oIn order to


arguments (let’s say either 2 or 3 arguments for simplicity)

accomplish the task, you can create two methods sum2num(int, int) and
sum3num(int,

oHowever, other programmers, as well


int, int) for two and three parameters respectively

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

Dr. Abed EL Safadi

Why Method Overloading?


DEFINING CLASSES 69
CHAPTER 2 -

Dr. Abed EL Safadi

Overloading Example 1

CHAPTER 2 - DEFINING CLASSES


70Output
Overloading by changing the number of parameters
Dr. Abed EL Safadi

Overloading Example 2

CHAPTER 2 - DEFINING CLASSES

71Output Overloading by changing the type of parameters


CHAPTER 2 - DEFINING CLASSES 72

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
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 thetime of declaration


2. Calling the various set methods
3. Initializing using constructorCHAPTER 2 - DEFINING CLASSES 73
Dr. Abed EL Safadi

Initialize Instance Variables


//code that initializes instance variables
◦ A constructor must have the same name as the class
◦ A constructor has no type returned, not even void
Dr. Abed EL Safadi
◦ Constructors are typically overloaded: A class can have multiple constructors

Initialize Instance Variables Using


Constructors CHAPTER 2 - DEFINING CLASSES 74

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){
}

Initialize Instance Variables Using


ConstructorsA constructor is called when an object of the class is created
using the newoperator ClassName objectName = new ClassName(anyArgs);

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

Date date1 = new Date();

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

Dr. Abed EL Safadi

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

CHAPTER 2 - DEFINING CLASSES 80


public Date(){
constructor day){[Link] = year;
year = 0;
month = null; With
day = 0;
public Date(int year, String month, int
} }
No arguments arguments constructor
public Date(){
constructor }
year = 2020;
public Date(int y, int d){ year = y;
month = “July”;
day = d;
day = 12;
}

Of course, the default constructor and the no-arguments


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

You might also like