Unit-II Classes, Objects and Methods
Unit-II Classes, Objects and Methods
UNIT II
Classes, Objects and Methods
2.1 Introduction
Defining Class,
Fields Declaration,
Methods Declaration,
Creating Objects
2.2 Visibility controls
2.3 Use of ‘this’ Keyword
2.4 Method Parameters and Method Overloading
2.5 Constructor and Constructor Overloading
2.6 Static Members
2.7 Finializer Method
2.8 Inheritance and It’s Types
2.9 Method Overriding
2.10 Final Variable, Method and Final Class
Introduction:
In object-oriented programming technique, we design a program using objects and classes.
An object in Java is the physical as well as a logical entity, whereas, a class in Java is a logical
entity only.
An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table,
car, etc. It can be physical or logical (tangible and intangible). The example of an intangible
object is the banking system.
1
BCA Sy 2023 Class Object and Method COCSIT, Latur
2
BCA Sy 2023 Class Object and Method COCSIT, Latur
Method in Java
In Java, a method is like a function which is used to expose the behavior of an object.
Advantage of Method
o Code Reusability
o Code Optimization
new keyword in Java
The new keyword is used to allocate memory at runtime. All objects get memory in Heap
memory area.
Object and Class Example: main within the class
In this example, we have created a Student class which has two data members id and name.
We are creating the object of the Student class by new keyword and printing the object's value.
Here, we are creating a main() method inside the class.
//Java Program to illustrate how to define a class and fields
//Defining a Student class.
class Student{
//defining fields
int id;//field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[]){
//Creating an object or instance
Student s1=new Student();//creating an object of Student
//Printing values of the object
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}
}
3
BCA Sy 2023 Class Object and Method COCSIT, Latur
We can have multiple classes in different Java files or single Java file. If you define multiple
classes in a single Java source file, it is a good idea to save the file name with the class name
which has main() method.
We can also create multiple objects and store information in it through reference variable.
4
BCA Sy 2023 Class Object and Method COCSIT, Latur
class Student{
int id;
String name;
}
class TestStudent3{
public static void main(String args[]){
//Creating objects
Student s1=new Student();
Student s2=new Student();
//Initializing objects
s1.id=101;
s1.name="Sonoo";
s2.id=102;
s2.name="Amit";
//Printing data
System.out.println(s1.id+" "+s1.name);
System.out.println(s2.id+" "+s2.name);
}
}
class Student{
int rollno; String name;
void insertRecord(int r, String n){ rollno=r; name=n; }
void displayInformation(){System.out.println(rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
s1.insertRecord(111,"Karan");
s1.displayInformation();
}}
5
BCA Sy 2023 Class Object and Method COCSIT, Latur
As you can see in the above figure, object gets the memory in heap memory area. The reference
variable refers to the object allocated in the heap memory area. Here, s1 and s2 both are
reference variables that refer to the objects allocated in memory.
File: TestEmployee.java
class Employee{
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id=i; name=n; salary=s;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1=new Employee();
e1.insert(101,"ajeet",45000);
e1.display();
}}
6
BCA Sy 2023 Class Object and Method COCSIT, Latur
There is given another example that maintains the records of Rectangle class.
class Rectangle{
int length, width;
void insert(int l, int w){ length=l; width=w; }
void calculateArea(){System.out.println(length*width);}
}
class TestRectangle1{
public static void main(String args[]){
Rectangle r1=new Rectangle();
r1.insert(11,5);
r1.calculateArea();
}
}
Anonymous object
Anonymous simply means nameless. An object which has no reference is known as an
anonymous object. It can be used at the time of object creation only.
If you have to use an object only once, an anonymous object is a good approach. For example:
new Calculation();//anonymous object
Calling method through a reference:
Calculation c=new Calculation();
c.fact(5);
Calling method through an anonymous object
new Calculation().fact(5);
7
BCA Sy 2023 Class Object and Method COCSIT, Latur
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile,
transient, etc. Here, we are going to learn the access modifiers only.
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
1) Private
The private access modifier is accessible only within the class.
8
BCA Sy 2023 Class Object and Method COCSIT, Latur
class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
2) Default
If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package. It cannot be accessed from outside the package. It provides
more accessibility than private. But, it is more restrictive than protected, and public.
3) Protected
The protected access modifier is accessible within package and outside the package but
through inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class. It provides more accessibility than the default modifer.
4) Public
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
Method in Java
In general, a method is a way to perform some task. Similarly, the method in Java is a
collection of instructions that performs a specific task. It provides the reusability of code. We
9
BCA Sy 2023 Class Object and Method COCSIT, Latur
can also easily modify code using methods. In this section, we will learn what is a method in
Java, types of methods, method declaration, and how to call a method in Java.
Method Declaration
The method declaration provides information about method attributes, such as visibility,
return-type, name, and arguments. It has six components that are known as method header,
Method Signature: Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. It specifies the
visibility of the method. Java provides four types of access specifier:
o Public: The method is accessible by all classes when we use public specifier in our
application.
10
BCA Sy 2023 Class Object and Method COCSIT, Latur
o Private: When we use a private access specifier, the method is accessible only in the
classes in which it is defined.
o Protected: When we use protected access specifier, the method is accessible within the
same package or subclasses in a different package.
o Default: When we do not use any access specifier in the method declaration, Java uses
default access specifier by default. It is visible only from the same package only.
Return Type: Return type is a data type that the method returns. It may have a primitive data
type, object, collection, void, etc. If the method does not return anything, we use void keyword.
Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must be subtraction(). A method is invoked by
its name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left
the parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be performed.
It is enclosed within the pair of curly braces.
Naming a Method
While defining a method, remember that the method name must be a verb and start with
a lowercase letter. If the method name has more than two words, the first name must be a verb
followed by adjective or noun. In the multi-word method name, the first letter of each word
must be in uppercase except the first word. For example:
It is also possible that a method has the same name as another method name in the same class,
it is known as method overloading.
11
BCA Sy 2023 Class Object and Method COCSIT, Latur
Types of Method
There are two types of methods in Java:
o Predefined Method
o User-defined Method
Predefined Method
In Java, predefined methods are the method that is already defined in the Java class libraries is
known as predefined methods. It is also known as the standard library method or built-in
method. We can directly use these methods just by calling them in the program at any point.
Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc. When we call any
of the predefined methods in our program, a series of codes related to the corresponding method
runs in the background that is already stored in the library.
Each and every predefined method is defined inside a class. Such as print() method is defined
in the java.io.PrintStream class. It prints the statement that we write inside the method. For
example, print("Java"), it prints Java on the console.
User-defined Method
The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.
Let's create a user defined method that checks the number is even or odd. First, we will define
the method.
12
BCA Sy 2023 Class Object and Method COCSIT, Latur
Static Method
A method that has static keyword is known as static method. In other words, a method that
belongs to a class rather than an instance of a class is known as a static method. We can also
create a static method by using the keyword static before the method name.
The main advantage of a static method is that we can call it without creating an object. It can
access static data members and also change the value of it. It is used to create an instance
method. It is invoked by using the class name. The best example of a static method is
the main() method.
Instance Method
The method of the class is known as an instance method. It is a non-static method defined in
the class. Before calling or invoking the instance method, it is necessary to create an object of
its class. Let's see an example of an instance method.
13
BCA Sy 2023 Class Object and Method COCSIT, Latur
InstanceMethodExample.java
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 is 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.
Note: It is called constructor because it constructs the values at the time of object creation. It
is not necessary to write a constructor for a class. It is because java compiler creates a default
constructor if your class doesn't have any.
14
BCA Sy 2023 Class Object and Method COCSIT, Latur
Note: We can use access modifiers while declaring a constructor. It controls the object
creation. In other words, we can have private, protected, public or default constructor in
Java.
Types of Java constructors
There are two types of constructors in Java:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
15
BCA Sy 2023 Class Object and Method COCSIT, Latur
The default constructor is used to provide the default values to the object like 0, null, etc.,
depending on the type.
The parameterized constructor is used to provide different values to distinct objects. However,
you can provide the same values also.
//Java Program to demonstrate the parameterized constructor.
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){ id = i; name = n; }
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student4 s1 = new Student4(111,"Karan");
//calling method to display the values of object
s1.display();
}
}
16
BCA Sy 2023 Class Object and Method COCSIT, Latur
Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a different
task. They are differentiated by the compiler by the number of parameters in the list and their
types.
17
BCA Sy 2023 Class Object and Method COCSIT, Latur
There are many differences between constructors and methods. They are given below.
A constructor is used to initialize the state A method is used to expose the behavior
of an object. of an object.
A constructor must not have a return type. A method must have a return type.
The Java compiler provides a default The method is not provided by the
constructor if you don't have any compiler in any case.
constructor in a class.
The constructor name must be same as the The method name may or may not be
class name. same as the class name.
There is no copy constructor in Java. However, we can copy the values from one object to
another like copy constructor in C++.
18
BCA Sy 2023 Class Object and Method COCSIT, Latur
There are many ways to copy the values of one object into another in Java. They are:
o By constructor
o By assigning the values of one object into another
o By clone() method of Object class
In this example, we are going to copy the values of one object into another using Java
constructor.
There can be a lot of usage of Java this keyword. In Java, this is a reference variable that
refers to the current object.
19
BCA Sy 2023 Class Object and Method COCSIT, Latur
Suggestion: If you are beginner to java, lookup only three usages of this keyword.
The this keyword can be used to refer current class instance variable. If there is ambiguity
between the instance variables and parameters, this keyword resolves the problem of
ambiguity.
20
BCA Sy 2023 Class Object and Method COCSIT, Latur
}}
It is better approach to use meaningful names for variables. So we use same name for
instance variables and parameters in real time, and always use this keyword.
You may invoke the method of the current class by using the this keyword. If you don't use the
this keyword, compiler automatically adds this keyword while invoking the method. Let's see
the example
class A{
void m(){System.out.println("hello m");}
void n(){
System.out.println("hello n");
this.m(); //m();//same as this.m()
}}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}
}
21
BCA Sy 2023 Class Object and Method COCSIT, Latur
The this() constructor call can be used to invoke the current class constructor. It is used to reuse
the constructor. In other words, it is used for constructor chaining.
class A{
A(){System.out.println("hello a");}
A(int x){
this();
System.out.println(x);
}
}
class TestThis5{
public static void main(String args[]){
A a=new A(10);
}}
class A{
A(){
this(5);
System.out.println("hello a");
}
A(int x){
System.out.println(x);
}
}
class TestThis6{
public static void main(String args[]){
A a=new A();
}}
22
BCA Sy 2023 Class Object and Method COCSIT, Latur
The this() constructor call should be used to reuse the constructor from the constructor. It
maintains the chain between the constructors i.e. it is used for constructor chaining. Let's see
the example given below that displays the actual use of this keyword.
class Student{
int rollno;
String name,course;
float fee;
Student(int rollno,String name,String course){
this.rollno=rollno;
this.name=name;
this.course=course;
}
Student(int rollno,String name,String course,float fee){
this(rollno,name,course);//reusing constructor
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
}
class TestThis7{
public static void main(String args[]){
Student s1=new Student(111,"ankit","java");
Student s2=new Student(112,"sumit","java",6000f);
s1.display();
s2.display();
}}
23
BCA Sy 2023 Class Object and Method COCSIT, Latur
this.rollno=rollno;
this.name=name;
this.course=course;
}
Student(int rollno,String name,String course,float fee){
this.fee=fee;
this(rollno,name,course);//C.T.Error
}
void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
}
class TestThis8{
public static void main(String args[]){
Student s1=new Student(111,"ankit","java");
Student s2=new Student(112,"sumit","java",6000f);
s1.display();
s2.display();
}}
The this keyword can also be passed as an argument in the method. It is mainly used in the
event handling. Let's see the example:
class S2{
void m(S2 obj){
System.out.println("method is invoked");
}
void p(){ m(this); }
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
}
}
24
BCA Sy 2023 Class Object and Method COCSIT, Latur
In event handling (or) in a situation where we have to provide reference of a class to another
one. It is used to reuse one object in many methods.
We can pass the this keyword in the constructor also. It is useful if we have to use one object
in multiple classes. Let's see the example:
class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}
class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}
We can return this keyword as an statement from the method. In such case, return type of the
method must be the class type (non-primitive). Let's see the example:
return_type method_name(){
return this;
}
Example of this keyword that you return as a statement from the method
class A{
25
BCA Sy 2023 Class Object and Method COCSIT, Latur
A getA(){
return this;
}
void msg(){System.out.println("Hello java");}
}
class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}
Let's prove that this keyword refers to the current class instance variable. In this program, we
are printing the reference variable and this, output of both variables are same.
class A5{
void m(){
System.out.println(this);//prints same reference ID
}
public static void main(String args[]){
A5 obj=new A5();
System.out.println(obj);//prints the reference ID
obj.m();
}
}
Finalize Method:
finalize() is a method of the Object class in Java. The finalize() method is a non-static and
protected method of java.lang.Object class. In Java, the Object class is superclass of all Java
classes. Being an object class method finalize() method is available for every class in Java.
Hence, Garbage Collector can call finalize() method on any Java object for clean-up activity.
finalize() method in Java is used to release all the resources used by the object before it is
deleted/destroyed by the Garbage collector. finalize is not a reserved keyword, it's a method.
Once the clean-up activity is done by the finalize() method, garbage collector immediately
destroys the Java object. Java Virtual Machine(JVM) permits invoking of finalize() method
26
BCA Sy 2023 Class Object and Method COCSIT, Latur
only once per object. Once object is finalized JVM sets a flag in the object header to say that it
has been finalized, and won't finalize it again. If user tries to use finalize() method for the same
object twice, JVM ignores it.
Java considers unreferenced objects that are not being used by any program execution or
objects that are no longer needed, as garbage.
Garbage collection is the process of destroying unused objects and reclaiming the unused
runtime memory automatically. By doing this memory is managed efficiently by
Java. Unrefrencing of objects is done in multiple ways as follows:
1. By anonymous object: Anonymous objects are those objects in Java which are created
without any reference variable. As a result, after creation, we have no way to access the
anonymous object.
new Student();
In the above code, even though an object of Student class is created, it has no reference
variable and cannot be used after creation, but it acquires memory.
27
BCA Sy 2023 Class Object and Method COCSIT, Latur
After the last statement s1 = s2 is executed, the first object becomes unreferenced and can be
considered for garbage collection.
The garbage collector is a part of Java Virtual Machine(JVM). Garbage collector checks the
heap memory, where all the objects are stored by JVM, looking for unreferenced objects that
are no more needed. And automatically destroys those objects. Garbage collector
calls finalize() method for clean up activity before destroying the object. Java does garbage
collection automatically; there is no need to do it explicitly, unlike other programming
languages.
The garbage collector in Java can be called explicitly using the following method:
System.gc();
System.gc() is a method in Java that invokes garbage collector which will destroy the
unreferenced objects. System.gc() calls finalize() method only once for each object.
In the above program, when the String object a holds value Hello World! it has a reference to
an object of the String class. But, when it holds a null value it does not have any reference.
Hence, it is eligible for garbage collection. The garbage collector calls finalize() method to
perform clean-up before destroying the object.
28
BCA Sy 2023 Class Object and Method COCSIT, Latur
The major advantage of performing clean-up before garbage collection is data resources or
network connections that are linked to unreferenced object are revoked and can be used again.
Cleanup ensures resources are not linked to objects unnecessarily and helps JVM in boosting
memory optimization and speed.
Finalization
Garbage collector always invokes finalize() method in java to perform clean-up activities
before destroying any object. This process of performing clean-up activities
using finalize() method is called finalization.
Note: For each object garbage collector calls finalize() method only once.
As mentioned earlier, finalize() is a protected method of the Object class in Java. Here is the
syntax:
Protected method: protected is an access specifier for variables and methods in java.
When a variable or method is protected it means it can be accessed within the class
where it's declared and other derived classes of that class.
In Java, all classes inherit the Object class directly or indirectly. finalize() method is
protected in Object class so that all classes in Java can override and use it.
finalize() method in Java is a method of the Object class that is used to perform clean-up
activity before destroying any object. It is called by Garbage collector before destroying the
objects from memory. finalize() method is called by default for every object before its deletion.
29
BCA Sy 2023 Class Object and Method COCSIT, Latur
This method helps Garbage Collector to close all the resources used by the object and helps
JVM in-memory optimization.
To understand this topic, you should have some knowledge of the following Java
Programming topics:
Garbage Collection in Java
Final Keyword in Java
Exception Handling in Java
Static Members
The static keyword in Java is used for memory management mainly. We can apply static
keyword with variables, methods, blocks and nested classes. The static keyword belongs to the
class than an instance of the class.
The static can be:
1. Variable (also known as a class variable)
2. Method (also known as a class method)
3. Block
4. Nested class
30
BCA Sy 2023 Class Object and Method COCSIT, Latur
s1.display();
s2.display();
}
}
31
BCA Sy 2023 Class Object and Method COCSIT, Latur
Counter(){
count++;//incrementing value
System.out.println(count);
}
public static void main(String args[]){
//Creating objects
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}
32
BCA Sy 2023 Class Object and Method COCSIT, Latur
Counter2(){
count++;//incrementing the value of static variable
System.out.println(count);
}
33
BCA Sy 2023 Class Object and Method COCSIT, Latur
class Calculate{
static int cube(int x){
return x*x*x;
}
34
BCA Sy 2023 Class Object and Method COCSIT, Latur
35
BCA Sy 2023 Class Object and Method COCSIT, Latur
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).
The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields of
the parent class. Moreover, you can add new methods and fields in your current class also.
36
BCA Sy 2023 Class Object and Method COCSIT, Latur
The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.
As displayed in the above figure, Programmer is the subclass and Employee is the superclass.
The relationship between the two classes is Programmer IS-A Employee. It means that
Programmer is a type of Employee.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
37
BCA Sy 2023 Class Object and Method COCSIT, Latur
On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We
will learn about interfaces later.
When one class inherits multiple classes, it is known as multiple inheritance. For Example:
38
BCA Sy 2023 Class Object and Method COCSIT, Latur
When a class inherits another class, it is known as a single inheritance. In the example given
below, Dog class inherits the Animal class, so there is the single inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in
the example given below, BabyDog class inherits the Dog class which again inherits the
Animal class, so there is a multilevel inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
39
BCA Sy 2023 Class Object and Method COCSIT, Latur
When two or more classes inherits a single class, it is known as hierarchical inheritance. In
the example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical
inheritance.
To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.
Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes.
If A and B classes have the same method and you call it from child class object, there will be
ambiguity to call the method of A or B class.
Since compile-time errors are better than runtime errors, Java renders compile-time error if you
inherit 2 classes. So whether you have same method or different, there will be compile time
error.
40
BCA Sy 2023 Class Object and Method COCSIT, Latur
41
BCA Sy 2023 Class Object and Method COCSIT, Latur
42
BCA Sy 2023 Class Object and Method COCSIT, Latur
new Honda2().run();
}
}
Q) What is blank or uninitialized final variable?
A final variable that is not initialized at the time of declaration is known as blank final
variable. If you want to create a variable that is initialized at the time of creating object and
once initialized may not be changed, it is useful. For example PAN CARD number of an
employee. It can be initialized only in constructor.
Example of blank final variable
class Student{
int id;
String name;
final String PAN_CARD_NUMBER;
...
}
Que) Can we initialize blank final variable?
Yes, but only in constructor. For example:
class Bike10{
final int speedlimit;//blank final variable
Bike10(){
speedlimit=70;
System.out.println(speedlimit);
}
43
BCA Sy 2023 Class Object and Method COCSIT, Latur
1. class A{
2. static final int data;//static blank final variable
3. static{ data=50;}
4. public static void main(String args[]){
5. System.out.println(A.data);
6. }
7. }
44