Chapter 5 Class, Objects, Methods, Constrctors and Inheritances
Chapter 5 Class, Objects, Methods, Constrctors and Inheritances
Chapter 5 Class, Objects, Methods, Constrctors and Inheritances
Or
Collection of objects is called class. It is a logical entity. Once a class has been
defined, we can create any number of objects belongs to that class.
For Example:
Fields
Methods
Constructors
Blocks
Nested class and interface
Once a class has been defined, we can create any number of objects belongs to that
class. Each object associated with data and Methods.
For Example “Fruit” is a class and Mango, Apple and Banana are objects.
class <class_name>
field; method;
1
Example:1
class Student
{
int id; //field or data member or instance variable
String name;
public static void main(String args[])
{
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);
}
}
Output:
O
Null
Example: 2
class Student
{
int id;
String name;
}
class TestStudent3
{
public static void main(String args[])
{
Student s1=new Student(); //Creating objects
Student s2=new Student();
s1.id=101; //Initializing objects
s1.name="Sonu";
s2.id=102;
s2.name="Monu";
System.out.println(s1.id+" "+s1.name); //Printing data
System.out.println(“ \n”);
System.out.println(s2.id+" "+s2.name);
}
}
Output:
101 Sonu
102 Monu
2
Multiple Classes:
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.
class Student
{
int id=1122;
String name="Amith";
}
//Creating another class TestStudent1 which contains the main method
class Student123
{
public static void main(String args[])
{
Student s1=new Student();
System.out.println(s1.id);
System.out.println(" \n");
System.out.println(s1.name);
}
}
Output:
1122
Amith
3
Object in Java:
The Object is the real-time entity having some state and behavior. In Java, Object is
an instance of the class having the instance variables as the state of the object and
the methods as the behaviour of the object. The object of a class can be created by
using the new keyword in Java Programming language.
Objects are run time entities in an object-oriented System. They may represent a
person, place, Place, Bank Account, a table of data or anu other item. that has state
and behavior is known as an object.
For example, a chair, pen, table, keyboard, bike, etc. It can be physical or logical.
class Parul
{
// Declaring and initializing string
String name = " PARUL UIVERSITY @ Vadodara";
public static void main(String[] args) // Main driver method
{
Parul obj = new Parul(); // using new keyword
// Print and display the object
System.out.println(obj.name);
}
}
Output:
PARUL UIVERSITY @ Vadodara
4
2.Using Object Cloning – clone() method:
Output:
5
3.Using newInstance() Method of Class class:
The newInstance() method of the Class class is also used to create an object. It calls
the default constructor to create the object. It returns a newly created instance of the
class represented by the object. It internally uses the newInstance() method of the
Constructor class.
Example:
public class CreateObjectExample4
{
void show()
{
System.out.println("A New Object Created.");
}
public static void main(String[] args)
{
try
{
//creating an instance of Class class
Class cls = Class.forName("CreateObjectExample4");
//creates an instance of the class using the newInstance() method
CreateObjectExample4 obj = (CreateObjectExample4) cls.newInstance();
//invoking the show() method
obj.show();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (InstantiationException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
}
}
6
Output:
import java.lang.reflect.*;
class Parul
{
// Member variables of this class
private String name;
// Constructor of this class
Parul() {}
// Method 1
// To set name of the string
public void setName(String name)
{
// This method refers to current object itself
this.name = name;
}
// Main driver method
public static void main(String[] args)
{
// Try block to check for exceptions
try
{
Constructor<Parul> constructor= Parul.class.getDeclaredConstructor();
Parul r = constructor.newInstance();
// Custom passing
r.setName("PIET @ Parul University");
System.out.println(r.name);
}
// Catch block to handle the exceptions
catch (Exception e)
{
7
// Display the exception on console
// using printStackTrace() method
e.printStackTrace();
}
}
}
Output:
5.Using deserialization
Serialization
import java.io.*;
class Persist
{
public static void main(String args[])
{
Try
{
//Creating the object
Student s1 =new Student(211,"ravi");
//Creating stream and writing the object
FileOutputStream fout=new FileOutputStream("f.txt");
ObjectOutputStream out=new ObjectOutputStream(fout);
out.writeObject(s1);
out.flush();
//closing the stream
out.close();
System.out.println("success");
}
catch(Exception e)
8
{
System.out.println(e);
}
}
}
Output:
Success
Deserialization:
import java.io.*;
class Depersist
{
public static void main(String args[])
{
Try
{
//Creating stream to read the object
ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
Student s=(Student)in.readObject();
//printing the data of the serialized object
System.out.println(s.id+" "+s.name);
//closing the stream
in.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output:
111
Ram
9
What is a method in Java?
Method Declaration:
10
Method Signature:
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:
Public: The method is accessible by all classes when we use public specifier
in our application.
Private: When we use a private access specifier, the method is accessible only
in the classes in which it is defined.
Protected: When we use protected access specifier, the method is accessible
within the same package or subclasses in a different package.
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:
Parameter List:
11
Method Body:
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
12
Example:1
Example:2
13
User-defined Method:
Let's create a user defined method that checks the number is even or odd. First, we
will define the method.
14
Example:
import java.util.Scanner;
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from the user
int num=scan.nextInt();
//method calling
findEvenOdd(num);
}
}
Output :
Enter the number: 12
12 is a even number
Types:
1.Static Methods: it is implement the behaviour of the class.
Static Method:
A static method in Java is a method that is part of a class rather than an instance
of that class.
Every instance of a class has access to the method.
Static methods have access to class variables (static variables) without using
the class's object (instance).
Only static data may be accessed by a static method
15
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.
16
Non-Static Example:
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();
Student s2=new Student();
s1.insertRecord(111,"William");
System.out.println(" \n");
s2.insertRecord(222,"Smith");
s1.displayInformation();
s2.displayInformation();
}
}
Output:
111 William
222 Smith
17
import java.io.*;
class Geek
{
public static String geekName = "";
public static void geek(String name)
{
geekName = name;
}
}
class GFG
{
public static void main(String[] args)
{
// Accessing the static method geek()
// and field by class name itself.
Geek.geek("Abhinav");
System.out.println(Geek.geekName);
// Accessing the static method geek()
// by using Object's reference.
Geek obj = new Geek();
obj.geek("Amith");
System.out.println(obj.geekName);
}
}
Output:
Abhinav
Amith
18
Method Overloading:
If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.
If we have to perform only one operation, having same name of the methods increases
the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a(int, int) for two parameters,
and b(int, int, int) for three parameters
19
1.Method Overloading: changing no. of arguments:
In this example, we have created two methods, first add() method performs addition
of two numbers and second add method performs addition of three numbers.
class Adding
{
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(Adding.add(100,200));
System.out.println(Adding.add(100,200,300));
}
}
Output:
300
600
20
2.Method Overloading: changing data type of arguments
In this example, we have created two methods that differs in data type. The first add
method receives two integer arguments and second add method receives two double
arguments.
class Adding
{
static int add(int a, int b)
{
return a+b;
}
static double add(double a, double b, double c)
{
return a+b+c;
}
}
class TestOverloading2
{
public static void main(String[] args)
{
System.out.println(Adding.add(100,200));
System.out.println(Adding.add(100.55,200.55,300.33));
}
}
Output:
300
601.4300000000001
21
Method Overriding:
If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.
In this example, we have defined the run method in the subclass as defined in the
parent class but it has some specific implementation. The name and parameter of the
method are the same, and there is IS-A relationship between the classes, so there is
method overriding.
In other words, If a subclass provides the specific implementation of the method that
has been declared by one of its parent class, it is known as method overriding.
class Vehicle
{
void run()
{
System.out.println("Vehicle is running");
}
}
class Bike extends Vehicle //Creating a child class
{
public static void main(String args[])
{
Bike obj = new Bike(); //creating an instance of child class
obj.run(); //calling the method with child class instance
}
}
22
Output:
Vehicle is running
//Java Program to illustrate the use of Java Method Overriding
//Creating a parent class.
Example:
class Vehicle
{
//defining a method
void run()
{
System.out.println("Vehicle is running");
}
}
//Creating a child class
class Bike2 extends Vehicle
{
//defining the same method as in the parent class
void run()
{
System.out.println("Bike Is Running Safely");
}
public static void main(String args[])
{
Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}
Output:
23
Constructor:
Default Constructor:
class Bike1
{
//creating a default constructor
Bike1()
{
System.out.println("Bike is created");
}
//main method
public static void main(String args[])
{
//calling a default constructor
Bike1 b=new Bike1();
}
}
Output:
Bike is created
24
1.Parameterized Constructor:
A constructor which has a specific number of
parameters is called a parameterized constructor. The parameterized constructor is
used to provide different values to distinct objects. However, you can provide the
same values also.
Example:
class Student4
{
int id;
String name;
Student4(int i, String n) //creating a parameterized constructor
{
id = i;
name = n;
}
void display() //method to display the values
{
System.out.println(id+" "+name);}
public static void main(String args[])
{
Student4 s1 = new Student4(111,"Karan"); //creating objects and passing values
Student4 s2 = new Student4(222,"Aryan"); //calling method to display the values of
object
s1.display();
s2.display();
}
}
Output:
111 Karan
222 Aryan
25
2.Constructor overloading in java:
The constructor overloading can be defined
as the concept of having more than one constructor with different parameters list, so
that every constructor can perform a different task.
26
Difference between constructor and method in Java
There are many differences between constructors and methods. They are given
below.
A constructor must not have a return type. A method must have a return
type.
The constructor name must be same as the class The method name may or may
name. not be same as the class name.
27
Encapsulation:
Wrapping up data and methods into a single unit is known as Encapsulation. The
data not accessible from out side the world and only access those methods, which
are wrapped in the class, it can access it.
Data
Informtion in And information out
Method
Example:
class Area
{
int length;
int breadth; // fields to calculate area
// constructor to initialize values
Area(int length, int breadth)
{
this.length = length;
this.breadth = breadth;
}
// method to calculate area
public void getArea()
{
int area = length * breadth;
System.out.println("Area: " + area);
}
}
class Main
{
public static void main(String[] args)
{
// create object of Area
// pass value of length and breadth
Area rectangle = new Area(5, 6);
rectangle.getArea();
}
}
Output:
30
28
Polymorphism:
Example:
class Shape
{
void draw()
{
System.out.println("drawing...");
}
}
class Rectangle extends Shape
{
void draw()
{
System.out.println("drawing rectangle...");
}
}
class Circle extends Shape
{
void draw()
{
System.out.println("drawing circle...");
}
}
29
class Triangle extends Shape
{
void draw()
{
System.out.println("drawing triangle...");
}
}
class TestPolymorphism2
{
public static void main(String args[])
{
Shape s;
s=new Rectangle();
s.draw();
s=new Circle();
s.draw();
s=new Triangle();
s.draw();
}
}
Output
drawing rectangle...
drawing circle...
drawing triangle...
30
Abstraction:
Abstraction refers to the act of representing essential feature without
including the background details or explanation. Classes use the abstraction
concepts and defined a list of abstract attributes.
Example:
for example, sending SMS where you type the text and send the message.
You don't know the internal processing about the message delivery.
Example:
31
}
Output:
32
Inheritance:
Inheritance is an important pillar of OOP (Object-Oriented
Programming). It is the mechanism in java by which one class is allowed to inherit
the features (fields and methods) of another class. In Java, inheritance means
creating new classes based on existing ones. A class that inherits from another
class can reuse the methods and fields of that class.
On the basis of class, there can be three types of inheritance in java: single, multilevel
and hierarchical.
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.
33
Example:
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);
}
}
Output:
Programmer salary is:40000.0
Bonus of Programmer is:10000
34
Multilevel Inheritance Example
When there is a chain of inheritance, it is known
as multilevel inheritance. Multilevel Inheritance in java involves inheriting a class,
which already inherited some other class. Multilevel Inheritance in Java is a type of
inheritance in which a class that is already inherited by another class, inherits another
class.
class Student
{
int reg_no;
void getNo(int no)
{
reg_no=no;
}
void putNo()
{
System.out.println("registration number= "+reg_no);
}
}
//intermediate sub class
class Marks extends Student
{
float marks;
35
void getMarks(float m)
{
marks=m;
}
void putMarks()
{
System.out.println("marks= "+marks);
}
}
class Sports extends Marks //derived class
{
float score;
void getScore(float scr)
{
score=scr;
}
void putScore()
{
System.out.println("score= "+score);
}
}
class MultilevelInheritanceExample
{
public static void main(String args[])
{
Sports ob=new Sports();
ob.getNo(123);
ob.putNo();
ob.getMarks(78);
ob.putMarks();
ob.getScore(68);
ob.putScore();
}
}
Output:
registration number= 123
marks= 78.0
score= 68.0
36
Hierarchical Inheritance:
Syntax:
Class Parent
{
//Data members and member functions of Parent Class
}
Class Derived-1 : access modifier Parent
{
//Data members and member functions of Derived-1 class
}
Class Derived-2 : access modifier Parent
{
//Data members and member functions of Derived-2 class
}
37
Example:
class Student
{
public void methodStudent()
{
System.out.println("The method of the class Student invoked.");
}
}
class Science extends Student
{
public void methodScience()
{
System.out.println("The method of the class Science invoked.");
}
}
class Commerce extends Student
{
public void methodCommerce()
{
System.out.println("The method of the class Commerce invoked.");
}
}
class Arts extends Student
{
public void methodArts()
{
System.out.println("The method of the class Arts invoked.");
}
}
public class HierarchicalInheritanceExample
{
public static void main(String args[])
{
Science sci = new Science();
Commerce comm = new Commerce();
Arts art = new Arts();
//all the sub classes can access the method of super class
sci.methodStudent();
38
comm.methodStudent();
art.methodStudent();
}
}
Output:
39
What is a multiple inheritance:
When a class inherits properties from many classes, this is
known as multiple inheritance. Multiple Inheritance is not supported by Java. But using Interfaces,
Multiple Inheritance is possible in Java.
Example:
interface A
{
public abstract void execute1();
}
interface B
{
public abstract void execute2();
}
class C implements A,B
{
public void execute1()
{
System.out.println("Haii.. I am from execute1");
}
public void execute2()
{
System.out.println("Haii.. I am from execute2");
}
}
class Main
{
public static void main(String[] args)
{
C obj = new C(); // creating object of class C
obj.execute1(); //calling method execute1
obj.execute2(); // calling method execute2
}
}
40
Output:
41
Hybrid inheritance:
the hybrid inheritance is the composition of two or more types of inheritance. The
main purpose of using hybrid inheritance is to modularize the code into well-
defined classes. It also provides the code reusability.
Single and Multiple Inheritance (not supported but can be achieved through
interface)
Multilevel and Hierarchical Inheritance
Hierarchical and Single Inheritance
Multiple and Multilevel Inheritance.
class GrandFather
{
public void show()
{
System.out.println("I am grandfather.");
}
}
//inherits GrandFather properties
class Father extends GrandFather
{
public void show()
{
System.out.println("I am father.");
42
}
}
//inherits Father properties
class Son extends Father
{
public void show()
{
System.out.println("I am son.");
}
}
//inherits Father properties
public class Daughter extends Father
{
public void show()
{
System.out.println("I am a daughter.");
}
public static void main(String args[])
{
Daughter obj = new Daughter();
obj.show();
}
}
Output:
I am a daughter.
43
Super keyword:
The super keyword in java is a reference variable that is used to refer to parent
class objects. An understanding of Inheritance and Polymorphism is needed in
order to understand the super keyword. The keyword “super” came into the
picture with the concept of Inheritance. It is majorly used in the following
contexts:
Example:
class Vehicle
{
int maxSpeed = 120;
}
class Car extends Vehicle // sub class Car extending vehicle
{
int maxSpeed = 180;
void display()
{
// print maxSpeed of base class (vehicle)
System.out.println("Maximum Speed: " + super.maxSpeed);
}
}
class Test // Driver Program
{
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
}
Output:
Maximum Speed: 120
44
2. Use of super with methods:
This is used when we want to call the parent
class method. So whenever a parent and child class have the same-named methods
then to resolve ambiguity we use the super keyword. This code snippet helps to
understand the said usage of the super keyword.
Example:
class Person
{
void message()
{
System.out.println("This is person class\n");
}
}
// Subclass Student
class Student extends Person
{
void message()
{
System.out.println("This is student class");
}
// Note that display() is
// only in Student class
void display()
{
// will invoke or call current
// class message() method
message();
// will invoke or call parent
// class message() method
super.message();
}
}
// Driver Program
class Test
{
public static void main(String args[])
{
Student s = new Student();
// calling display() of Student
s.display();
}
}
45
Output:
Example:
class Person
{
Person()
{
System.out.println("Person class Constructor");
}
}
// subclass Student extending the Person class
class Student extends Person
{
Student()
{
// invoke or call parent class constructor
super();
System.out.println("Student class Constructor");
}
}
class Test // Driver Program
{
public static void main(String[] args)
{
Student s = new Student();
}
}
Output:
46