Professional Documents
Culture Documents
CS 241: OBJECT
ORIENTED
PROGRAMMING
Dr. Ibrahim Eldesoky
Ibrahim_desoky@hotmail.com
2
Defining Classes
Motivation
Class Declaration
import statement;
public
A public class is accessible by any class.
Class Members
private
A private member is accessible only by the class itself.
protected
We will talk about it later
9
class Time {
Constructor methods
Constructor methods
• Here is a constructor for the Time class:
public Time () {
hour = 0;
minute = 0;
second = 0;
}
• This constructor does not take any arguments, as indicated by
the empty parentheses ().
Constructor methods
• Here is another form to the constructor. It has parameter list that is
identical to the list of the instance variables.
Constructor methods
• Can the Constructor be overloaded like other
methods? which means that you can provide multiple
constructors with different parameters.
• Yes, it can.
Constructor methods
• Remember:
• Although constructors look like methods, you never invoke them
directly, you have to use new operator.
class Time {
Instantiating objects
hour 0
t1
minute 0
second 0
hour 11
t2
minute 8
second 3
22
// how to instantiate Time objects
class Time {
t1.hour=11; t1.minute=8;t1.second=3;
hour 0
t1
minute 0
second 0
hour 11
t1
minute 8
second 3
24
class TimeCall {
}
}
25
class TimeCall {
class Time {
class TimeCall {
t1.setHour(10);
System.out.println (t1.getHour());
}}
28
Printing objects
• you can invoke this method from the main by using print or
println() method as follows:
System.out.print (t1);
Time: hour minute second