Intro To Classes and Objects
Intro To Classes and Objects
Lecture 2
1 / 33
Contents
2 Class: A Blueprint
6 Variables in Java
2 / 33
Introduction to class and Object
This lecturer note sketches the foundation on which the entire Java programming
Language is developed.
After knowing the basic building blocks of programming languages like Operators,
Conditional statements, Loops, now it’s the time to proceed towards different concepts of
Object Oriented Programming Languages(OOPs).
Java Classes and Objects are one of the core building blocks of Java applications,
frameworks and APIs (Application Programming Interfaces).
Java is an object-oriented programming language where everything in Java is associated
with classes and objects.
Let us now look deep into the real-world, where we find everything around us are objects
such as cars, dogs, humans, etc.
These objects have some states and behaviors which are used to differentiate them
properly.
If we consider a human i,e a student, then its state are name, branch,regdno, sec, marks
etc. and the behavior like reading, playing, eating etc.
3 / 33
Continue...
Our basic aim is to relate the real wold objects with software objects and class is one of the
concept of Object-Oriented Programming which revolve around the real-life entities i,e
objects.
Class in Java logically describes how an object will behave and what the object will contain.
4 / 33
Continue...
Let us thing about a blue print of a house which contains all the details about the floors,
doors, windows, etc.
Based on these logical descriptions we build the house and now this house becomes a
physical entity or object in this real world. In a software domain, we can think of the class
as a blueprint of a house that logically describes the characteristics of a house, a
physically existing entity or object.
Since many houses can be made from the same description, we can create many objects
from a class.
5 / 33
Class: A Blueprint
A class is an user defined template that logically describes the states and behaviours of an
object.
In general, class declarations can include variables(States) and methods(Behaviors).
The variables and methods declared inside the class are called as class members.
Data Members(Variables)
Member Functions(Methods)
Syntax to define a class in Java
class <identifier (className) >
{
Data Members (Variables);
Member Functions (Methods);
}
Here class is a user defined data type followed by an identifier class name. In Java format,
the first letter of the class name must be capital letter.
6 / 33
Continue...
For example, let us define the states and behaviors of a student object inside a class
Student.
c l a s s Student
{
S t r i n g name ;
i n t regdNo ;
S t r i n g branch ;
double cgpa ;
void input ( )
{
\\ Body p a r t o f t h e F u n c t i o n
}
void display ( )
{
\\ Body p a r t o f t h e F u n c t i o n
}
} / / End o f c l a s s
The student class has four variables (name, regdNo, branch, cgpa) and two methods
(input(), display( )). These variables and methods defined within a class are called as data
members and member function of the class respectively.
7 / 33
Object: A Physical Entity
Basically, objects form the basic unit of OOPs with behaviours and identity. As mentioned
previously, a class provides the blueprints for objects.
Class has no existences, it’s only act as a template for an physical entity named object.
The most important thing about class is that it defines a new data type. So as long as we
don’t create any variable for the new data type class, we can’t realize the presence of a
class. So an object is an instance or variable of a class.
NB: Class acts as a logical description for an object and Object is the physical
realization of a class.
8 / 33
Continue...
Example: Let us consider the above class student to create an object.
So, once you define a class, we can create objects as much as we want as follows.
Student S2=new Student( );
Student S3=new Student( ); and so on...
So, without a class, there can be no objects and without objects, no computation can take
place in Java.
Thus, a class is the basis of all computations in Java. Objects creation is not enough to
establish the relationship between a class and objects. For this, objects must access the
members (Data members and member functions) of the class.
10 / 33
Continue...
p u b l i c c l a s s Student
{
S t r i n g name ;
i n t regdNo ;
S t r i n g branch ;
double cgpa ;
void display ( )
{
System . o u t . p r i n t l n ( ” The name o f t h e s t u d e n t i s : ” +name ) ;
System . o u t . p r i n t l n ( ” The regdNo o f t h e s t u d e n t i s : ” +regdNo ) ;
System . o u t . p r i n t l n ( ” The branch o f t h e s t u d e n t i s : ” +branch ) ;
System . o u t . p r i n t l n ( ” The cgpa o f t h e s t u d e n t i s : ” +cgpa ) ;
}
p u b l i c s t a t i c v o i d main ( S t r i n g args [ ] )
{
Student S1=new Student ( ) ;
Student S2=new Student ( ) ;
S1 . name= ” Rahul ” ;
S1 . regNo =123456;
S1 . branch= ”CSE” ;
S1 . cgpa = 9 . 8 ;
S2 . name= ” Sachin ” ;
S2 . regNo =652354;
S2 . branch= ”CSE” ;
S2 . cgpa = 9 . 7 ;
S1 . d i s p l a y ( ) ;
S2 . d i s p l a y ( ) ;
}
} / / End o f c l a s s
11 / 33
Continue...
As shown in the figure 3, we have created two objects S1 an S2 which are initialized
directly using dot operator inside the main program. The display() is used to show the
required output of the program.
As shown in the figure 3, it is not always the best way to provide initial values to all the
objects by accessing the data members directly.
This type of initialization will not work for some cases where data members are declared as
private modifier (will be discus later on) for Java in order to archive data hidden concept.
In order to make Java program more stable, it is always preferable to use member function
for object initialization.
12 / 33
Continue...
Initialization through normal member function
A class comprised of both data members and member functions. A member function
of a class is a function that has its definition or its prototype within the class definition
like any other variable.
It operates on any object of the class of which it is a member and has access to all
the members of a class for that object.
Program 2.2 Create a class student with data members name, regdNo, branch and
cgpa. Craete two objects of the class and provide the initial value to the members
using a setter function input() and display them using display().
NB:The program is in next Slide
} / / End o f c l a s s 14 / 33
Continue...
Output:
Enter the information of the Student
Rahul
123456
CSE
9.8
The name of the student is:Rahul
The regdNo of the student is: 123456
The branch of the student is: CSE
The cgpa of the student is:9.8
Enter the information of the Student
Sachin
652354
CSE
9.7
The name of the student is:Sachin
The regdNo of the student is: 652354
The branch of the student is: CSE
The cgpa of the student is: 9.7
Initialization through a constructor
We will discuss about this in next lecturer note i,e.L 3.
15 / 33
Use of Multiple Java Classes
In all the previous sections, we have considered only one class namely Student and used
the main() method along with all other members inside the class .
It is also possible to define multiple classes under a single file name. Using multiple
classes means that we can create an object of a class and use it in another class.
Also, we can access this object in multiple classes. One class contains all the properties,
fields and methods while the other class contains a main() method in which we write the
code which has to be executed.
We often use this concept for proper organization and management of classes.
NB: We have to keep one thing in mind that no mater how many classes we are
creating inside a single file, the name of the file should be same as the name of the
class which contains the main( ) method and it needs to declare as public.
Now, we will understand this with the help of the previous Student class example, along
with a new class Alpha that contains the main( ) method as follows:
Program 2.3:Create a class Book with instance variables name, ISBN, author, price and
methods setData(), display(). Write a Java program to create two objects of Book class to
input details of two different books and display the details. Enclose main() method inside
another class Alpha.
16 / 33
Continue...
i m p o r t Java . u t i l . Scanner ;
c l a s s Book
{
S t r i n g name ;
i n t ISBN ;
Stri ng author ;
double p r i c e ;
v o i d setData ( )
{
Scanner sc=new Scanner ( System . i n ) ;
System . o u t . p r i n t l n ( ” E n t e r t h e i n f o r m a t i o n o f t h e Book . ” ) ;
name=sc . n e x t ( ) ;
ISBN=sc . n e x t I n t ( ) ;
a u t h o r =sc . n e x t ( ) ;
p r i c e =sc . nextDouble ( ) ;
}
void display ( )
{
System . o u t . p r i n t l n ( ” The name o f t h e Book i s : ” +name ) ;
System . o u t . p r i n t l n ( ” The ISBN o f t h e Book i s : ” +ISBN ) ;
System . o u t . p r i n t l n ( ” The a u t h o r o f t h e Book i s : ” + a u t h o r ) ;
System . o u t . p r i n t l n ( ” The p r i c e o f t h e Book i s : ” + p r i c e ) ;
}
} / / End o f c l a s s Book
p u b l i c c l a s s Alpha {
p u b l i c s t a t i c v o i d main ( S t r i n g args [ ] ) {
Book B1=new Book ( ) ;
Book B2=new Book ( ) ;
B1 . setData ( ) ;
B1 . d i s p l a y ( ) ;
B2 . setData ( ) ;
B2 . d i s p l a y ( ) ;
}
} 17 / 33
Continue...
Output:
Enter the information of the Book.
ICP
2356
PRABHAT
450.6
The name of the Book is: ICP
The ISBN of the Book is: 2356
The author of the Book is: PRABHAT
The price of the Book is: 450.6
Enter the information of the Book.
DSA
7896
SANTOSH
651.90
The name of the Book is: DSA
The ISBN of the Book is: 7896
The author of the Book is: SANTOSH
The price of the Book is: 651.9
18 / 33
Continue...
19 / 33
Variables in Java
A variable is a container which holds the value while the Java program is executed. A
variable is assigned with a data type. Variable is a name of memory location.
20 / 33
Continue...
i m p o r t j a v a . u t i l . Scanner ;
class Circle
{
double rad ; / / INSTANCE VARIABLE
v o i d getData ( )
{
Scanner sc=new Scanner ( System . i n ) ;
System . o u t . p r i n t l n ( ” E n t e r t h e r a d i u s ” ) ;
rad=sc . nextDouble ( ) ;
}
void calculate ( )
{
double p i = 3 . 1 4 1 ; / / LOCAL VARIABLE
System . o u t . p r i n t l n ( ” The area o f t h e r e c t a n g l e i s : ” + ( p i * rad * rad ) ) ;
}
}
p u b l i c c l a s s Alpha
{
p u b l i c s t a t i c v o i d main ( S t r i n g args [ ] )
{
C i r c l e C1=new C i r c l e ( ) ;
C1 . getData ( ) ;
C1 . c a l c u l a t e ( ) ;
}
} / / End o f c l a s s Alpha
21 / 33
Memory Allocation for Objects in Java
Memory allocation is a process by which computer programs and services are assigned
with physical or virtual memory space.
As Objects are variables of type class, memory for the objects are also created.
The Java Memory Allocation for variables is divided into three sections as follows:
Heap Area: The memory space for an object is always allocated on heap area.
Heap space in Java is used for dynamic memory allocation for Java objects using
the new operator.
Stack Area: Stack is a portion of the memory where the local primitive variables or
local object reference variables are stored. Such local variables live on the Stack
until the block or method in which they are declared is being executed.
Class Area: Will be discuss in next lecturer note i,e L 3.
let us try to understand the memory allocation areas by using of following program.
Program 2.5: Create a class student with data members name, regdNo, branch and cgpa.
Craete two objects of the class and provide the initial vaule to the members and display
them.
22 / 33
Continue...
Objects and instance variables continue to live on Heap until they are referenced by their
reference variables.
Once an object is no longer referenced by any reference variable, it is eventually removed
from Heap by the Garbage Collector.
As long as we don’t initialize the objects with values, JVM always provides its default
values to initialize the instance variables in heap area.
NB: Size of a object is equals to the total size of instance variables of the corresponding
class. 24 / 33
Passing Arguments into a member function of a class
Similar to functions in other programming languages, Java methods accept input from the
caller through its arguments. Arguments provide information to the method from outside
the scope of the method.
When we write any member function inside the class, we must determine the number and
type of the arguments required by that method. You declare the type and name for each
argument in the method signature.
NB: While initializing, the data type of instance variable must match with function
argument type.
26 / 33
Continue...
Passing Reference Data Type Arguments(Objects as function Arguments)
Although Java is strictly pass by value, still it is possible to pass reference type
(Basically object) to all the member function of a class. When we pass a primitive
type to a method, it is passed by value.
But when we pass an object to a method, the situation changes dramatically,
because objects are passed by what is effectively call-by-reference.
While creating a variable of a class type, we only create a reference to an object.
Thus, when we pass this reference to a method, the parameter that receives it will
refer to the same object as that referred to by the argument.
This effectively means that objects act as if they are passed to methods by use of
call-by-reference. Changes to the object inside the method do reflect in the object
used as an argument.We can pass Object of any class as parameter to a method in
Java.
We can access the instance variables of a class using dot operator using the object
passed as argument inside the called method.
NB:It is good practice to initialize instance variables of an object before
passing object as parameter to method otherwise it will take default initial
values.
Program 2.7: Define a complex class called Comp with instance variables real, img
and instance methods input(int,int), display(), calculate(). Write a Java program to
add two complex numbers.
The prototype of add method is: void calculate(Complex, Complex).
27 / 33
Continue...
c l a s s Comp
{
int real ;
i n t img ;
v o i d i n p u t ( i n t p , i n t q ) / / Passing P r i m i t i v e Data Type Arguments
{
r e a l =p ;
img=q ;
}
v o i d c a l c u l a t e (Comp C11 , Comp C22 ) / / Passing Reference Type Arguments
{
r e a l =C11 . r e a l +C22 . r e a l ;
img=C11 . img+C22 . img ;
}
void display ( )
{
System . o u t . p r i n t l n ( r e a l + ” + i ” +img ) ;
}
} / / End o f Class Comp
p u b l i c c l a s s Alpha
{
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] args )
{
Comp C1=new Comp ( ) ;
Comp C2=new Comp ( ) ;
C1 . i n p u t ( 1 0 , 2 0 ) ;
C2 . i n p u t ( 3 0 , 4 0 ) ;
Comp C3=new Comp ( ) ;
C3 . c a l c u l a t e ( C1 , C2 ) ;
C1 . d i s p l a y ( ) ;
C2 . d i s p l a y ( ) ;
System . o u t . p r i n t l n ( ” The sum o f C1 and C2 i s : ” ) ;
C3 . d i s p l a y ( ) ;
}} / / End o f Class Alpha 28 / 33
Continue...
Output:
10+i20
30+i40
The sum of C1 and C2 is:
40+i60
As shown in the figure 7, C1, C2, C3 are references created in stack area and they refers
to the corresponding memory locations in heap area. C1, C2, C3 are actual arguments
passed inside the calling function. C11 and C22 are references passed as formal
arguments to the called function calculate(Comp,comp) and both c11 and C22 refer to the
same memory locations that refer by C1 and C2. As C3 is used to call the method
calculate(C1,C2) inside the main(), so the addition of instance variables real and img of C1
and C2 will be store in C3 instance variable real and img respectively.
29 / 33
Returning Objects from Methods in Java
30 / 33
Continue...
c l a s s Time
{ i n t hr , min ;
void input ( i n t p , i n t q )
{ h r =p ; min=q ;}
Time c a l c u l a t e ( Time T11 , Time T22 ) / / F u n c t i o n r e t u r n i n g O b j e c t
{
Time T33=new Time ( ) ;
T33 . min=T11 . min+T22 . min ; i n t x =0;
i f ( T33 . min>=60)
{
x=T33 . min / 6 0 ; T33 . min=T33 . min%60;
}
T33 . h r =T11 . h r +T22 . h r +x ;
r e t u r n T33 ;
}
void display ( )
{
System . o u t . p r i n t l n ( h r + ” : ” +min ) ; }} / / End o f Class Time
p u b l i c c l a s s Alpha
{ p u b l i c s t a t i c v o i d main ( S t r i n g [ ] args ){
Time T1=new Time ( ) ;
Time T2=new Time ( ) ;
T1 . i n p u t ( 1 , 5 0 ) ;
T2 . i n p u t ( 3 , 4 0 ) ;
Time T3=new Time ( ) ;
T3=T3 . c a l c u l a t e ( T1 , T2 ) ;
T1 . d i s p l a y ( ) ;
T2 . d i s p l a y ( ) ;
System . o u t . p r i n t l n ( ” The sum o f T1 and T2 i s : ” ) ;
T3 . d i s p l a y ( ) ;
}} / / End o f Class Alpha
31 / 33
Continue...
As shown in the figure 8, we have created another object T33 inside the called function
calculate(Time,Time) that returns this object. The addition of hr and min values of T11 and
T22 will be move to hr and min of T33.The calculate() function will return the T33 object to
calling function inside the main() method.Finally the values of T33 object is copied to T3
object. Now if we call the display function using T3 object, it will display the result of
addition of T1 and T2.
32 / 33
References
33 / 33