Chapter Three: Classes and Objects
Chapter Three: Classes and Objects
02/10/22 1
•Classes are “blueprints”for creating a
group of objects.
A bird class to create bird objects
A car class to create car objects
A shoe class to create shoe objects
•The blueprint defines
The class’s state/attributes as variables
The class’s behavior as methods
02/10/22 2
Cont…
We’ve already seen...
•How to use classes and the objects created from
them...
Scanner input = newScanner(System.in);
•How to invoke their methods using the dot notation
int num = input.nextInt();
02/10/22 3
Cont…
•A class is a logical framework or blue print or
template of an object .
•A Java class uses variables to define data
fields and methods to define behaviors
• A class is a programmer defined data type for
which access to data is restricted to specific set of
functions in that class.
02/10/22 4
Cont…
02/10/22 5
Example –class song
02/10/22 6
Example-class student
• An object which recorded information about a University of
Gondar student might record a first name, a last name and
an identification number.
• We would represent this as follows in Java.
class Student {
public String firstName;
public String lastName;
public String idNumber;
}
02/10/22 7
Example-class student
02/10/22 8
Example-class student
02/10/22 9
Instance variable
•A variable that is created inside the class but
outside the method.
•Instance variable doesn't get memory at
compile time.
•It gets memory at runtime when
object(instance) is created.
•That is why, it is known as instance variable.
02/10/22 10
Local variables
02/10/22 11
class variable
•A class variable or static variable is defined in a
class, but there is only one copy regardless of
how many objects are created from that class.
02/10/22 12
Definition and declaration of a class:
Syntax:
class ClassName{
//member attributes (instance or class
variables)
//member Methods
02/10/22 13
Definition and declaration of a
class:
• A class definition defines the class blueprint.
02/10/22 14
Class Data Fields
02/10/22 15
Class methods
02/10/22 16
Class Methods
• A class definition typically includes one or more
methods, which carry out some action with the
data.
02/10/22 17
Class methods
• The structure of a method includes a method
signature and a code body:
[access modifier] return type
method name (list of arguments)
{
statements, including local variable
declarations
}
02/10/22 18
• The first line shows a method signature consisting of
access modifier - determines what other classes and
subclasses can invoke this method.
return type - what primitive or class type value will
return from the invocation of the method.
• If there is no value return, use void for the return
type.
02/10/22 19
method name - follows the same identifier rules as
for data names.
normally, a method name begins with a lower case
letter.
list of arguments - the values passed to the method.
statements - the code to carry out the task for the
particular method.
02/10/22 20
Example
class Circle{
float r;
void showArea(){
float area = r*r*PI;
System.out.println(“The area is:” + area);
}
void showCircumference(){
float circum=2* PI*r;
System.out.println(“The circumference is:” + circum);
}
...}
02/10/22 21
Objects
• An object is an instance of a class. It can be uniquely identified by its name and
defined state, represented by the values of its attributes in a particular time.
02/10/22 22
Creating an object from class
Creating an object is a two-step process.
1.Creating a reference variable
Syntax:
<class idn><ref. idn>; eg. Circle c1;
02/10/22 23
Objects ….
Syntax:
<ref. idn>.<member>;
02/10/22 24
Example
Consider the already defined class Circle and define another
class TestClass
class TestClass{
public static void main(String args[]){
Circle c1 = new Circle();
c1.r = 2.3;
c1.showArea();
c1.showCircumference();
}}
The new keyword is used to allocate memory at runtime.
02/10/22 25
Object creating example
class Student{
int id;//data member (also instance variable)
String name;//data member(also instance variable)
public static void main(String args[]){
Student s=new Student();//creating object of Student
System.out.println(s.id); //output=?
System.out.println(s.name); //output=?
}
}
02/10/22 26
Creating multiple objects by one type
We
onlycan create multiple objects by
one type only as we do in case of
primitives.
i.e like int x,y,z; in primitves
We can say Student s1,s2,s3;
02/10/22 27
Class activity 1
Create a rectangle class that calculate
the area of rectangle.
Create an object from the rectangle
class to access class members.
Create an insert method to insert width
and length of a rectangle.
Create calculateArea method to
compute the area of a rectangle
respectively.
02/10/22 28
class Rectangle{
int length;
int width;
void insert(int l,int w){
length=l;
width=w;
}
02/10/22 29
void calculateArea(){
System.out.println(length*width);
}
public static void main(String args[]){
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea(); } }
02/10/22 30
Visibility Modifiers
The following are common visibility
modifiers
Public
Default
Private
Protected
02/10/22 31
•You can use the public visibility modifier
for classes, methods, and data fields to
denote that they can be accessed from any
other classes(even outside package).
02/10/22 33
•The private modifier restricts access to its
defining class
•The default modifier restricts access to a
package,
•The public modifier enables unrestricted access.
•If a class is not defined public, it can be
accessed only within the same package.
02/10/22 34
protected
•Often it is desirable to allow subclasses to
access data fields or methods defined in the
superclass, but not allow non subclasses to
access these data fields and methods.
•To do so, you can use the protected keyword.
•A protected data field or method in a superclass
can be accessed in its subclasses.(will see in the next
chapter)
02/10/22 35
Summery on visibility modifiers
Accessible to: public protected Package private
(default)
Same Class Ye s Ye s Ye s Ye s
Class in package Ye s Ye s Ye s No
Subclass in Ye s Ye s No No
different package
Non-subclass Ye s No No No
different package
02/10/22 36
The static keyword
02/10/22 37
When can we access static variable
• When a class is loaded by the virtual machine all the
static variables and methods are available for use.
• Hence we don’t need to create any instance of the
class for using the static variables or methods.
• Variables which don’t have static keyword in the
definition are implicitly non static.
02/10/22 38
Class staticDemo{ Example
public static int a = 100; // All instances of staticDemo have this variable as a common variable
public int b =2 ;
public static showA(){
System.out.println(“A is “+a); } }
public static void main(String args[]){
staticDemo.a = 35; // when we use the class name, the class is loaded, direct
access to a without any instance
staticDemo.b=22; // ERROR this is not valid for non static variable
staticDemo demo = new staticDemo();
demo.b = 200; // valid to set a value for a non static variable after creating
an instance.
staticDemo.showA(); //prints 35
}}
02/10/22 39
Static and Non-static
• We can access static variables without creating an
instance of the class
• As they are already available at class loading time,
we can use them in any of our non static methods.
• We cannot use non static methods and variables
without creating an instance of the class as they are
bound to the instance of the class.
• They are initialized by the constructor when we
create the object using new operator.
02/10/22 40
final fields
41
Creating objects of a class
aCircle = new Circle();
bCircle = new Circle() ;
bCircle = aCircle;
P Q P Q
42
Automatic garbage collection
The object Q
does not have a reference and
cannot be used in future.
43
Constructor
•Objects are created by using the
operator new in statements such as
Circle c=new Circle();
•The following expression invokes a
special kind of method known as a
constructor
new Circle();
•Constructors are used to Create objects
and Initialize the instance variables
02/10/22 44
Constructor
02/10/22 45
Constructor
•When an object is created, a constructor for
that class is called.
• If no constructor is defined, a default
constructor is called.
02/10/22 47
• The default constructor calls the default parent
constructor (super()) and initializes all instance
variables to default value i.e
zero for numeric types,
null for object references,
false for booleans.
• Default constructor is created only if there are no
constructors.
• If you define any constructor for your class, no
default constructor is automatically created.
02/10/22 48
Differences between methods and
constructors
02/10/22 49
02/10/22 50
02/10/22 51
The this key word
• Use this to refer to the current object.
• Use this to invoke other constructors of the object.
02/10/22 52
• The called constructor is named this()
• Another common form of a constructor is
called a copy constructor
02/10/22 53
// copy constructor
otherCar.model, otherCar.numLiters,
otherCar.horsepower, otherCar.numDoors,
otherCar.year);
}
02/10/22 54
Destructor
A destructor is also a member function whose name is the
same as the class name but is preceded by tilde(“~”).
It is automatically by the compiler when an object is
destroyed.
02/10/22 55
Example
class TEST {
int Regno,Max,Min,Score;
Public:
TEST( ){…} // Default Constructor
TEST (int Mregno,int Mscore) {// Parameterized Constructor
Regno = Mregno;Max=100;Min=40;Score=Mscore;
}
~ TEST ( ) { // Destructor
S.O.P(“Test Over”;}
}
02/10/22 56
• Class provides one or more methods
• Method represents task in a program
• Describes the mechanisms that actually perform
its tasks
• Hides from its user the complex tasks that it
performs
• Method call tells method ato perform its task
• Classes contain one or more attributes
• Specified by instance variables
• Carried with the object as it is used
02/10/22 57
• Declaring more than one public class in the same
file is a compilation error.
02/10/22 58
Class activity 2
Create a class called Welcome that print
message "Welcome to java program!" .
Create a displayMessage method with
empty parameter in class Welcome to
display the above text.
Create an other class WelcomeTest to test
the above Welcome class
Create an object on WelcomeTest class to
invoke the method on Welcome class.
02/10/22 59
public class Welcome{
public void displayMessage(){
System.out.println( "Welcome to java program!" );
}
}
public class WelcomeTest
{
public static void main( String args[] )
{
Welcome disp= new Welcome();
disp.displayMessage();
}}
02/10/22 60
Class activity 3
Create a class called GradeBook that print
message( "Welcome to GradeBook for \n%s!“,
courseName) .
Create a displayMessage method with a
parameter in class Welcome to display the above
text with course name given from the keyboard.
Create an other class GradeBookTest to test the
above Welcome class by Creating GradeBook
object and invoke displayMessage method.
02/10/22 61
public class GradeBook
{
// display a welcome message to the GradeBook user
public void displayMessage( String courseName ) •
{
System.out.printf( "Welcome to the grade book for\n%s!\n",
courseName );
}
}
62
import java.util.Scanner; // program uses Scanner
63
• Normally, objects are created with new. One
exception is a string literal that is contained in
quotes, such as "hello". String literals are
references to String objects that are
implicitly created by Java.
• A compilation error occurs if the number of
arguments in a method call does not match
the number of parameters in the method
declaration.
64
set and get methods
65
Class activity 4
Create a class called GradeBook that print text
message( "Welcome to GradeBook for \n%s!“,
getCoursename()) .
create set method to set courseName and get
method to retrieve the courseName.
Create a displayMessage method with a
parameter in class Welcome to display the above
text with course name given from the keyboard.
Create an other class GradeBookTest to test the
above Welcome class by Creating GradeBook
object and invoke displayMessage method.
02/10/22 66
public class GradeBook{
Instance variable courseName
•
private String courseName; // course name for this GradeBook
69
Initializing Objects with Constructors
• Constructors
• Initialize an object of a class
• Java requires a constructor for every class
• Java will provide a default no-argument constructor if none is
provided
• Called when keyword new is followed by the class name and
parentheses
70
Class activity 5
Create a class called GradeBook with
constructor to initialize the courseName.
create set method to set courseName and get
method to retrieve the courseName.
Create a displayMessage method with a
parameter in class Welcome to display the above
text with course name given from the keyboard.
Create an other class GradeBookTest to test the
above Welcome class by Creating GradeBook
object and invoke displayMessage method.
02/10/22 71
public class GradeBook{
private String courseName; // course name for this GradeBook
public GradeBook( String name ) { Constructor to initialize
courseName variable
courseName = name; // initializes courseName
} // end constructor
// method to set the course name
public void setCourseName( String name ){
return courseName;
} // end method getCourseName
72
public void displayMessage()
{
// this statement calls getCourseName to get the
// name of the course this GradeBook represents •
System.out.printf( "Welcome to the grade book for\n%s!\n",
getCourseName() );
} // end method displayMessage
73
public class GradeBookTest
{
// main method begins program execution
public static void main( String args[] ) Call constructor to create first grade
•
{ book object
// create GradeBook object
GradeBook gradeBook1 = new GradeBook(
" Introduction to Java Programming" );
GradeBook gradeBook2 = new GradeBook(
"Data Structures in Java" ); Create second grade book object
Any ?
End of chapter 3
02/10/22 75