Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 75

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…

• A class has a state (field) and behavior (method).

Fields: Say what a class is

Methods: Say what a class does

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

• This is a class definition.


• The identifier of the class being defined is Student.

• Objects of this class will have three fields;


firstName
 lastName
 idNumber
• The purpose of the Student class is to allow us to store
together these three related data items.

02/10/22 8
Example-class student

• It seems appropriate to store these three data items


together because they are the firstName, lastName
and idNumber respectively of one person.

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

•Variables that are declared in a method are


called local variables.

•They are called local because they can only be


referenced and used locally in the method in
which they are declared

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.

•It's common to define static final variables


(constants) that can be used by all methods, or
by other classes.

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.

• The behaviors/operations of a class are implemented


methods. Also known as member functions

• The state of the class is stored in its data members.


Also known as fields, attributes, or instance
variables

02/10/22 14
Class Data Fields

• A class definition typically includes one or more


fields that declare data of various types.

• When the data field declaration does not assign an


explicit value to the data, default values will be used

02/10/22 15
Class methods

• Objects are sent messages which in turn call


methods.

• Methods may be passed arguments and may return


something as well.

• Methods are available to all instances of the class.


• Like data members, methods are also referenced
using the dot operator.

02/10/22 16
Class Methods
• A class definition typically includes one or more
methods, which carry out some action with the
data.

• Methods resemble the functions and subroutines in


other languages.

• A method will be called, or invoked, by code in


some other method.

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.

• An object represents something with which we can interact in a program.

• A class represents a concept, and an object represents the embodiment of a


class. A class is a blueprint for an object.

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;

2. Setting the reference with the newly created object.


Syntax:
<ref. idn> = new <class idn>(…);
c1 = new Circle();
•The two steps can be done in a single statement
Circle c2 = new Circle();

02/10/22 23
Objects ….

Accessing members of an Object:


•To access members of an object we use ‘.’ (dot)
operator together with the reference to an object.

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

• If no visibility modifier is used, then by


default the classes, methods, and data
fields are accessible by any class in the
same package.
•Also called default modifier.
02/10/22 32
•The private modifier makes methods and data
fields accessible only from within its own class.
It indicates that instance variables are
accessible only to methods of the class; this is
known as data hiding

•The get and set methods are used to read


and modify private properties.

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

• The static keyword is used when a member variable


of a class has to be shared between all the instances
of the class.

• All static variables and methods belong to the class


and not to any instance of the class

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

• The keyword final means: once the value is set,


it can never be changed.

• Typically used for constants.

static final int BUFSIZE=100;


final double PI=3.14159;

41
Creating objects of a class
aCircle = new Circle();
bCircle = new Circle() ;

bCircle = aCircle;

Before Assignment After Assignment

aCircle bCircle aCircle bCircle

P Q P Q

42
Automatic garbage collection

 The object Q
does not have a reference and
cannot be used in future.

 The object becomes a candidate for automatic garbage


collection.

 Java automatically collects garbage periodically and


releases the memory used to be used in the 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

•Constructors must have the same name as the class


itself.
•Constructors do not have a return type: not even
void.
•Constructors are similar to methods, but with some
important differences.

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.

•It's common to have multiple constructors


taking different numbers of parameters.
•Before a constructor is executed, the
constructor for the parent class is called
02/10/22 46
Types of constructors
• Default constructor: this initializes objects based
on default values, takes no argument.
• If you don't define a constructor for a class, a
default parameter less constructor is
automatically created by the compiler.

• Parameterized constructor: these initialize


objects based on some parameter values.

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

•There is no return type given in a constructor


signature (header).

•The value is this object itself so there is no need to


indicate a return value.

•There is no return statement in the body of the


constructor. Look at the car class…

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.

• When several alternative constructors are written


for a class, we reuse code by calling one constructor
from another

02/10/22 52
• The called constructor is named this()
• Another common form of a constructor is
called a copy constructor

• A copy constructor takes a single argument


that is the same type as the class itself and
creates a copy of it.

02/10/22 53
// copy constructor

public Car(Car otherCar) {

this(otherCar.vin, otherCar.color, otherCar.make,

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.

Destructors are usually used to deallocate memory and do


other cleanup for a class object and its class members when
the object is destroyed.

A destructor is called for a class object when that object


passes out of scope or is explicitly deleted.

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

public class GradeBookTest{


public static void main( String args[] ){
Scanner input = new Scanner( System.in );
GradeBook myGradeBook = new GradeBook();
System.out.println( "Please enter the course name:" );
String nameOfCourse = input.nextLine(); // read a line of text
System.out.println(); // outputs a blank line
myGradeBook.displayMessage( nameOfCourse );}}

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

• private instance variables


• Cannot be accessed directly by clients of the object
• Use set methods to alter the value
• Use get methods to retrieve the value

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

// method to set the course name


public void setCourseName( String name )
{ set method for courseName
courseName = name; // store the course name
} // end method setCourseName

// method to retrieve the course name


public String getCourseName()
get method for courseName
{
return courseName;
} // end method getCourseName
public void displayMessage()
{
System.out.printf( "Welcome to the grade book for\n%s!\n",
getCourseName() );}}
67
import java.util.Scanner; // program uses Scanner

public class GradeBookTest{


public static void main( String args[] ) •
{
// create Scanner to obtain input from command
window
Scanner input = new Scanner( System.in );

// create a GradeBook object and assign it to


myGradeBook
GradeBook myGradeBook = new GradeBook();

// display initial value of courseName


System.out.printf( "Initial course name is: %s\n\n",
myGradeBook.getCourseName() );
Call get method for courseName
68
// prompt for and read course name
System.out.println( "Please enter the course name:" );
String theName = input.nextLine(); // read a line of
text
myGradeBook.setCourseName( theName ); // set the •
course name Call set method for courseName
System.out.println(); // outputs a blank line

// display welcome message after specifying course


name
myGradeBook.displayMessage();
} // end main Call displayMessage

} // end class GradeBookTest

Initial course name is: null

Please enter the course name:


Introduction to Java Programming

Welcome to the grade book for


Introduction to Java Programming!

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

courseName = name; // store the course name


} // end method setCourseName

// method to retrieve the course name


public String getCourseName(){

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

} // end class GradeBook

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

// display initial value of courseName for each GradeBook


System.out.printf( "gradeBook1 course name is: %s\n",
gradeBook1.getCourseName() );
System.out.printf( "gradeBook2 course name is: %s\n",
gradeBook2.getCourseName() );
}}

gradeBook1 course name is: Introduction to Java Programming


gradeBook2 course name is: Data Structures in Java
74
Reading assignment
Composition
UML class diagram

Any ?
End of chapter 3
02/10/22 75

You might also like