Object Oriented Programming
with JAVA
Anand Kumar , Assistant Professor
Computer Science & Engineering
UNIT-5
Object oriented programming:
Outline
Introduction of Classes and objects: concepts of classes and objects
Declaring objects
Assigning object reference variables
Methods
Constructors
Access control
Garbage collection,
usage of static with data and methods
usage of final with data
Overloading methods and constructors,
Parameter passing - call by value,
Recursion
Nested classes.
Classes and Object
Introduction to Class and object
Introduction to Class and object
Introduction to Class and object
Introduction Of Class and Object
Class
Class is a plan or model or template
Class is a blue print of object
Class is used to declare variables & methods
Project means collection of classes
Once class is created then we can create any no. of objects
for a class
'class' keyword is used to create Classes in java
Classes will not exist physically
Object
Object
Any real-world entity is called as Object
Objects exist physically
Objects will be created based on the Classes
Without having the class, we can' create object (class is mandatory to
create objects)
Object creation means allocating memory in JVM
'new' keyword is used to create the object
Program for class and object
class Kapil
{
int x = 5;
public static void main(String[] args)
{
Kapil myObj = new Kapil();
publSystem.out.println(myObj.x);
}
}
Method
Coding Convention for Methods
Method name can have any no. of words without spaces
Recommended to start method name with lowercase letter
If method name contains multiple words, then recommended to write
first word all characters in lowercase and from second word onwards
every word first character in Uppercase
Note: Variables & Methods naming conventions are same. But methods
will have parenthesis ( ( ) ) variables will not have parenthesis.
class Student {
{ public static void main(String [ ] args)
private int roll; {
private char grade; Student s=new Student( );
private float per; s.setData();
public void setData( ) s.showData();
{ }
roll=10; }
grade=‘A’l
per=66.5f;
}
public void showData( )
{
S.O.P(“Roll, grade and percentage is
”+roll,grade,per);
}
}
class Use
Initializing Data Member at Runtime
public void showDa )
{
S.O.P(“Roll is ”+roll);
S.O.P(“Grade is ”+grade);
S.O.P(“Percentage is ”+per);
}
}
class UseStudent
{
public static void main(String [ ] args)
{
Student s=new Student( );
s.setData();
s.showData( );
}
}
Creating Parameterized Methods
class Student
{
private int roll;
private char grade;
private float per;
public void setData(int r, char g, float p)
{
roll=r;
grade=g;
float=p;
}
public void showData( )
{
S.O.P(“Roll is ”+roll +“\nGrade is ”+grade+“\nPercentage is ”+per);
}
}
cla) Creating Parameterized Methods
{
Scanner kb=new Scanner(System.in);
Student s=new Student( );
S.O.P(“Enter roll, grade and percentage ”);
int roll=kb.nextInt( );
char grade=kb.next( );
float per=kb.nextFloat( );
s.setData(roll,grade,per);
s.showData( );
}
}
Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is
called when an instance of the class created.
At the time of calling constructor, memory for the object is allocated
in the memory.
It is a special type of method which is used to initialize the object.
Every time an object is created using the new() keyword, at least one
constructor is called.
It calls a default constructor if there is no constructor available in the
class. In such case, Java compiler provides a default constructor by
default.
There are two types of constructors in Java: no-arg constructor, and
parameterized constructor.
• Rules for creating Java constructor
There are two rules defined for the constructor.
1) Constructor name must be the same as its class name
2) A Constructor must have no explicit return type
3) A Java constructor cannot be abstract, static, final, and synchronized
Constructor
Rules of the constructor
Constructor name must be same as Class Name
Constructor cannot take any return type but if we write any return
type then the code is valid but it is considered as normal method
We cannot return any value from the constructor
Constructors can take one or parameters
Default Constructor
In Java, a constructor is said to be default constructor if it does not
have any parameter. Default constructor can be either user defined or
provided by JVM.
Constructor
If a class does not contain any constructor, then during runtime JVM
generates a default constructor which is known as system define
default constructor.
If a class contain a constructor with no parameter, then it is known as
default constructor defined by user. In this case JVM does not create
default constructor
Based on the number of parameters, constructors are classified into
following 2 types,
1) 0 Parameterized Constructor
2) 2) Parameterized Constructor
Perform Inter constructor calls
• Example :- public void show( )
class Box {
{ S.O.P(“Length= ”+this.l);
private int l,b,h; S.O.P(“Breadth= ”+this.b);
public Box( int l, int b, int S.O.P(“Height= ”+this.h);
h) }
{ }
this.l=l;
this.b=b;
this.h=h;
}
Perform Inter constructor calls
• Example :- }
class Box public Box(Box P)
{ {
private int l,b,h; this(P.l, P.b, P.h);
public Box( int l, int b, int h) }
{ public void show( )
this.l=l; {
this.b=b; S.O.P(“Length= ”+this.l);
this.h=h; S.O.P(“Breadth= ”+this.b);
} S.O.P(“Height= ”+this.h);
public Box(int s) }
{ }
this(s,s,s);
Garbage Collector
• We will understand this concept through a program…
• WAP to create a class called Employee having the following
data members.
An ID for storing unique id allocated to every employee.
name of employee
age of employee.
• Also provide following methods –
1. A parameterized constructor to initialize name and age.ID should
also be initialized in this cons
2. A method show() to display ID, name and age.
Example
class Employee
{
private int ID;
private String name;
private int age;
private static int nextId=1;
public Employee(String name, int age)
{
this.name=name;
this.age=age;
this.ID=nextId++;
}
public void show()
{
System.out.println("Id= "+ID+"\nName= "+name+"\nAge= "+age);
}
public void showNextId()
{
System.out.println("Next employee id will be "+nextId);
}}
Example
class UseEmployee
{
public static void main(String [] args)
{
Employee e=new Employee("Amit",25);
Employee f=new Employee("Rakesh",35);
Employee g=new Employee("Sumit",45);
e.show();
f.show();
g.show();
e.showNextId();
f.showNextId();
g.showNextId();
}
}
Garbage Collector Example continued
class UseEmployee
{
public static void main(String [] args)
{
// same as previous //
{
Employee x=new Employee("Ram",38);
Employee y=new Employee("Ajay",29);
x.show();
y.show();
x.showNextId();
y.showNextId();
System.gc();
System.runFinalization();
}
}
Garbage Collector
class Employee
{
// same as previous //
protected void finalize( )
{
--nextId;
}
}
* In order to call garbage collector on programmer’s request, we have to call methods
gc() and runFinalization( ).
The “Object” Class
• In Java every class by default inherits a class named
• This inheritance is done by Java and cannot be avoided by any programmer.
• Object class is the Super/Parent class of every class. It is super daddy class.
• It is present in the package java.lang.
• Object class has 8 methods in it. Hence, every class has at least 8 methods.
• finalize( ) method is one of them and we Override this method.
The “this” Keyword
• The “this” keyword in java is a predefined object reference available inside every non
static method of a class.
• On calling a method, the java compiler transfers the address of the object to the called
method.
• This address is copied inside the “this” reference. In short “this” reference
points to the object which is currently being used to call a method.
• Two major benefits of using “this” reference
1. We can use the local variables by using the same name as that of the data
members of class.
2. We can perform inter constructor call using “this”.
Using “static” Keyword
• The keyword static can be used at three situation i.e.
1. static data members
2. static methods
3. static blocks
4. static classes(Can be used only with nested class or inner class and not the outer class)
“static” Data members
• Usually, a non static data members is allocated in RAM only when an object is
created.
• static members are saved in RAM once, i.e. they are independent of the objects.
• A data member is made static when it should display same number change
for all objects.
Both a and b will get space in memory when
• For example, Object of class Data gets created.
class Data
{
int a; What if b is made static???
int b;
}
class Data
Objects and Classes
Static member
{
Class member
int a;
static int b; Shared member
} a 30,40 a
class UseData
{ 10 b 20
public static void main(String [ ] args)
{
Data d1=new Data( );
Data d2=new Data( );
d1.a=10;
d1 d2
d2.a=20;
System.out.println(d1.a+“\n”+d2.a); RAM
d1.b=30;
d2.b=40;
System.out.println(d1.b+“\n”+d2.b);
}
}
Features of “static” Data member
• Gets allocated in RAM as soon as program is executed, irrespective of the object.
• Only a single copy is made.
• Since, they are object independent they should be accessed using class name.
Data.b=30;
Data.b=40;
• Static members are kept in Permanent Generation area of RAM.
• Local variables cannot be made static i.e. not inside a method.
Example
class Employee
{
private int ID;
private String name;
private int age;
private static int nextId=1;
public Employee(String name, int age)
{
this.name=name;
this.age=age;
this.ID=nextId++;
}
public void show()
{
System.out.println("Id= "+ID+"\nName= "+name+"\nAge= "+age);
}
public void showNextId()
{
System.out.println("Next employee id will be "+nextId);
}}
“final” Data Members
• Any data member whose value must remain unchanged throughout the program and
cannot be altered once initialized, then in this we can prefix such data members with
keyword
final.
• Example :-
class Circle
{
private int radius;
private static final double pie=3.14159;
• It’s value will remain unchanged. Remember the data member Math.PI, it is declared
the same way. They behave like constants.
“final” Data Members
• The initialization of final data member can either be done explicitly while declaring or through con-
structors at run time only once. But in all the constructors defined in a class.
• Once explicitly initialized at declaration then it cannot be initialized again using constructors.
• Local variables can be made final as well.
• Java strongly recommends that when any data members is both final and static in nature then it
should be named in upper case. Example, private final static double PI=3.14159.
It’s not a rule but a professional coding convention.
Example
class Data class Data
{ {
final int a; final static int a;
public Data(int static
x) {
{ a=10;
a=x; }
} public static void main(String
} [ ] args)
{
System.out.println(A.a);
}
“final” Methods
• final is used with methods whose functionality remains same throughout i.e. in base as
well as derived classes.
• Methods which are declared finals cannot be overridden in derived classes. But they
do get inherited.
class A class B extends A
{ {
public final void display( ) public void display( )
{ {
--------- ---
} }
} }
Examples
class A class C
{
{
public final void display()
p s v main(String [] arg)
{
{
----
B obj=new B();
}
obj.display();
}
}
class B extends A
}
{
public void print()
{
super.display();
}
}
“final” Methods
• abstract methods cannot be made final and vise versa. Since, a method is made ab-
stract because of its unknown functionality, so they can be accordingly
modified in their derived classes. Whereas, a method is made final so that it’s
functionality should never change throughout the hierarchy.
• abstract methods can be called using derived class object but cannot be
overridden.
• Even method main() can be made final.
“final” Classes
• Those classes which are prefixed with keyword final cannot be inherited in Java.
• For example, class String is a final class and no other class can inherit it.
• Classes are made final in cases where the data member or methods are sensitive
enough that they should not be altered at any cost.
• Is there any other way through which we can prevent a class from being inherited???
(Just for knowledge!)
“final” Classes
final class A
{
----
----
}
class B extends A
{
----
----
}
“final” Classes
• Though, final classes cannot be inherited but final classes can inherit other classes.
• For example, every class does inherit the class Object and hence a final class also
does inherit the class Object.
Method Overloading in Java
If a class has multiple methods having same name but
different in parameters, it is known as Method Overloading.
Program:
Program for Changing no. of arguments
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
changing data type of arguments
class Adder{
static int add(int a, int b)
{
return a+b;}
static double add(double a, double b)
{ return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Constructor overloading in Java
In Java, we can overload constructors like methods. The constructor
overloading can be defined as the concept of having more than one
constructor with different parameters so that every constructor can
perform a different task.
public class Student {
//instance variables of the class
int id;
String name;
Student(){
System.out.println("this a default constructor");
}
Student(int i, String n){
id = i;
name = n;
}
Program Count…
public static void main(String[] args) {
Student s = new Student();
System.out.println("\nDefault Constructor values: \n");
System.out.println("Student Id : "+s.id + "\
nStudent Name : "+s.name);
System.out.println("\nParameterized Constructor values: \n");
Student student = new Student(10, "David");
System.out.println("Student Id : "+student.id + "\
nStudent Name : "+student.name);
}
x
Output:
Default Constructor values:
Student Id : 0
Student Name : null
Parameterized Constructor values:
Student Parameterized Constructor values:
Student Id : 10
Student Name : David
Call by Value in Java
We call a method passing a value, it is known as call by value.
class Operation{
int data=50;
void change(int data){
data=data+100;//changes will be in the local variable only
}
public static void main(String args[]){
Operation op=new Operation();
System.out.println("before change "+op.data);
op.change(500);
System.out.println("after change "+op.data);
Recursion in Java
Recursion in java is a process in which a method calls itself
continuously. A method in java that calls itself is called recursive
method.
It makes the code compact but complex to understand.
class GFG {
int fact(int n)
{ int result;
if (n == 1) return 1;
result = fact(n - 1) * n;
return result;
}
Program
class Recursion {
public static void main(String[] args)
{
GFG f = new GFG();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
}
Nested Class
Java inner class or nested class is a class that is declared
inside the class or interface.
If a class is declared with in another class, then this concept is
called as Inner classes or nested classes
Syntax
class A{
Class B{
}
}
Nested Class
If a class contains other class, then it is called as outer class or top-level class
Class declared inside the outer class is called as inner class
We have following 2 types of inner classes
1. non-static Inner classes
2. static Inner classes
Object and Classes
Thank You!!!
www.paruluniversi
ty.ac.in