0% found this document useful (0 votes)
11 views55 pages

Java Inheritance and Its Types Explained

It's OODP unit 2

Uploaded by

rshraddha283
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views55 pages

Java Inheritance and Its Types Explained

It's OODP unit 2

Uploaded by

rshraddha283
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

​ Unit:II Inheritance – Types of Inheritance-Super Keyword- Method Overrriding-

Dynamic method Dispatch– Abstract classes and methods- Final classes-Object Class –
Inner Class - Packages – Defining Packages – Finding Packages And CLASSPATH -Importing
Packages - Interfaces – Defining an Interface, Implementing Interface and Extending
Interfaces .

[Link]
●​ The process of deriving a new class from an old program is called inheritance.
●​ Old class of java is called as base class or super class or parent class and the new
class of java is called as subclass/derived class/child class.
●​ Inheritance represents the IS-A relationship which is also known as
a parent-child relationship.

Why use inheritance in java

o​ For Method Overriding (so runtime polymorphism can be achieved).


o​ For Code Reusability.

Terms used in Inheritance

o​ Class: A class is a group of objects which have common properties. It is a template or


blueprint from which objects are created.
o​ Sub Class/Child Class: Subclass is a class which inherits the other class. It is also
called a derived class, extended class, or child class.
o​ Super Class/Parent Class: Superclass is the class from where a subclass inherits
the features. It is also called a base class or a parent class.
o​ Reusability: As the name specifies, reusability is a mechanism which facilitates you
to reuse the fields and methods of the existing class when you create a new class.
You can use the same fields and methods already defined in the previous class.

The syntax of Java Inheritance

class Subclass-name extends Superclass-name


{
//methods and fields
}

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

Types of Inheritance:

Inheritance can be of any one following types


1.​Single inheritance (Only one superclass)
2.​Multiple inheritance (Several super classes)
3.​Hierarchical inheritance (One superclass, many subclasses)

4.​Multilevel inheritance(Derived from a derived class)


[Link] Inheritance(Combination of two inheritances)

Multiple inheritance cannot be used directly in java. This concept is


implemented by interface concepts in java

[Link] a superclass:

The sub class (the class that is derived from another class) is called a derived class. The
class from which it's derived is called the base class or super class.
The following figure illustrates these two types of classes:

[Link] a subclass:
Subclass is a class which is formed newly

Syntax for defining a subclass:


Class subclassname extends superclassname
{
Variable declaration;
Method declaration;
}

Pictorial representation of inheritance


(a)Single inheritance (b)Hierarchical
Inheritance

A
A

D
B C
B
(c )Multilevel (d)Multiple
inheritance inheritance

A A B

C
C

Single inheritance

The method of inheriting the properties from one super class to one sub class is called
single inheritance.

It consists of one base class and one derived class.

Example program1: Single inheritance

class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
[Link]();
}}

Output:

barking...
eating...

Example program2

class Room​ //base class


{
int length,breadth;
Room(int x,int y)

{
length=x;

breadth=y;
}

int area()
{

return(length*breadth);
}
}

class Bedroom extends Room​ //derived class using base class named Room
{

int height;

Bedroom(int x,int y, int z)


{

super(x,y);
height=z;

}
int volume()

{
return(length*breadth*height);

}
}
// Main class
public classsingleinheritance

{
public static void main(String ars[])

Bedroom room1=new Bedroom(14,12,10);


int area1=[Link]();

int volume1=[Link]();
[Link]( Area1= +area1);

[Link]( Volume1= +volume1);


}
}

Output:
Area1=168

Volume1=1680

Example program3:Single inheritance

class A

{
int x;
int y;

int get(int p, int q)


{

x=p;
y=q;

return(0);
}

void Show()
{

[Link](x);
}

class B extends A
{
public static void main(String args[])

{
B a = new B();

[Link](5,6);
[Link]();
}

Output:
5

Multilevel Inheritance
A general necessity in object oriented programming is the use of a derived class as a super
class.

A ->B->C is known as inheritance path.

A derived class with multilevel base classes is declared as follows.

class A
{
………………
………………
}
……………….
class B extends A

{
}
class C extends B

{
}

Example Program: Multilevel inheritance


class Animal{
void eat()
{
[Link]("eating...");}
}
class Dog extends Animal
{
void bark()
{
[Link]("barking...");}
}
class BabyDog extends Dog
{
void weep()
{
[Link]("weeping...");
}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
[Link]();
[Link]();
[Link]();
}}

Output:

weeping...
barking...
eating...

Example Program2:
class students //base class
{
private int sno;
private String sname;
public void setstud(int no,String name)
{
sno=no;
sname=name;
}
public void putstud()
{
[Link]( Student No: +sno);
[Link]( Student Name: +sname);

}
}

class marks extends students //derived or intermediate base class


{

protected int mark1,mark2;


public void setmarks(int m1,int m2)

{
mark1=m1;

mark2=m2;
}

public void putmarks()


{
[Link]( Mark1: +mark1);
[Link]( Mark2: +mark2);
}

}
class finaltot extends marks // derived class

{
private int total;

public void calc()


{

total=mark1+mark2;
}

public void puttotal()


{

[Link]( Total: +total);


}

public static void main(String args[])


{
finaltot f=new finaltot();

[Link](100, ABC );
[Link](78,89);

[Link]();
[Link]();

[Link]();
[Link]();

}
}

Example Program2:Multilevel Inheritance

class Base
{

void bmsg()
{
[Link]( Welcome to base class );

}
}

class Derive1 extends Base


{
void derive1msg()

{
[Link]( Derive1msg );

}
}

class Derive2 extends Derive1


{

void derive2msg()
{

[Link]( Derive2msg );
}

}
class Multilevel

{
public static void main(String args[])
{

Derive2 d2=new Derive2();


d2.derive2msg();

d2.derive1msg();
[Link]();

}
}

Output:
Derive2msg

Derive1msg
Welcome to base class

Hierarchical inheritance

Class A is a super class of both class B and class C i.e one super class has many sub
classes. Some features of one level are shared by many lower level cases

ACCOUNT

CURRENT
SAVINGS

FIXED DEPOSIT

MEDIUM LONG
SHORT

Example Program: Hierarchical inheritance

public class A
{

void DisplayA()

{
[Link]( I am in A );

}
}

public class B extends A

{
void DisplayB()

{
[Link]( I am in B );

}
}

public class C extends A

{
void DisplayC()
{

[Link]( I am in C );
}}
public class Mainclass
{

[Link]( Calling for subclass C );


C c=new C();

[Link]();
[Link]();

[Link]( Calling for subclass B );


B b=new B();

[Link]();
[Link]();
}

Output:
Calling for subclass C

I am in A
I am in C

Calling for subclass B


I am in A

I am in B

2.1.3. Protected Member:

The private members of a class cannot be openly accessed external class. Only functions of
that class can access the private data fields directly. As discussed previously, however,
occasionally it may be essential for a subclass to access a private member of a base class. If
you make a private member public, then someone can access that member. So, if a member
of a base class wants to be (directly) accessed in a subclass and yet still stop its direct
access external class, you must declare that member as protected.

Following table gives the difference

Modifier Class Subclass World


Public Y Y Y
Protected Y Y N
Private Y N N

Following program illustrates how the functions of a subclass can directly access a
protected member of the base class
For example, let's consider a series of classes to describe two types of shapes: rectangles
and triangles. These two shapes have definite general properties height and a width (or
base).

This could be depicted in the world of classes with a class Shapes from which we can derive
the two other ones : Rectangle and Triangle

public class Shape

protected double height; // To hold height.


protected double width; //To hold width or
base public void setValues(double height,
double width) {

[Link] = height;
[Link] = width;

}
}

public class Rectangle extends Shape

{
public double getArea()

{
return height * width; //accessing protected members

}
}

public class Triangle extends Shape


{
public double getArea()

{
return height * width / 2; //accessing protected members

}
}

public class TestProgram

{
public static void main(String[] args)

{
//Create object of Rectangle.

Rectangle rectangle = new Rectangle();

//Create object of Triangle.

Triangle triangle = new Triangle();

//Set values in rectangle object


[Link](5,4);

//Set values in trianlge object

[Link](5,10);

//​ Display the area of rectangle.


[Link]("Area of rectangle : " +[Link]());

//​ Display the area of triangle.


[Link]("Area of triangle : " +[Link]());

}
}

Output :

Area of rectangle : 20.0


Area of triangle : 25.0

[Link] Constructor

1.​ super can be used to refer immediate parent class instance variable.
2.​ super can be used to invoke immediate parent class method.

3.​ super() can be used to invoke immediate parent class constructor.


A Subclass constructor is used to build the instance variables of both the subclass and the
superclass.

The subclass constructor uses the keyword super to call up the constructor method of
the superclass. Keyword super is used subject to the subsequent conditions.

1.​Super may only be used within a subclass constructor method.

2.​ The call to super class constructor must show as the first statement inside
the subclass constructor.

[Link] parameters in the super class must equal to the order and type of the
instance variable declared in the base class

class Animal
{
Animal()
{
[Link]("animal is created");

}
}
class Dog extends Animal{
Dog()

{
super();
[Link]("dog is created");
}

}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();

}
}

Output:
animal is created

dog is created

2.2. Super Keyword in Java

The super keyword in Java is a reference variable which is used to refer immediate parent
class object.
Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.

Usage of Java super Keyword


1.​ super can be used to refer immediate parent class instance variable.
2.​ super can be used to invoke immediate parent class method.
3.​ super() can be used to invoke immediate parent class constructor.

1) super is used to refer immediate parent class instance variable.

We can use super keyword to access the data member or field of parent class. It is used if
parent class and child class have same fields.

class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
[Link](color);//prints color of Dog class
[Link]([Link]);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
}}
Output
black
white

In the above example, Animal and Dog both classes have a common property color. If we
print color property, it will print the color of current class by default. To access the parent
property, we need to use super keyword.

2) super can be used to invoke parent class method

The super keyword can also be used to invoke parent class method. It should be used if
subclass contains the same method as parent class. In other words, it is used if method is
overridden.

class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void eat(){[Link]("eating bread...");}
void bark(){[Link]("barking...");}
void work(){
[Link]();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
}}

Output:

eating...
barking...

In the above example Animal and Dog both classes have eat() method if we call eat()
method from Dog class, it will call the eat() method of Dog class by default because priority
is given to local.

To call the parent class method, we need to use super keyword.

3) super is used to invoke parent class constructor.

The super keyword can also be used to invoke the parent class constructor. Let's see a
simple example:

class Animal{
Animal(){[Link]("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
[Link]("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}

Output:

animal is created
dog is created
Note: super() is added in each class constructor automatically by compiler if there is no
super() or this().

As we know well that default constructor is provided by compiler automatically if there is


no constructor. But, it also adds super() as the first statement.

Another example of super keyword where super() is provided by the compiler


implicitly.

class Animal{
Animal(){[Link]("animal is created");}
}
class Dog extends Animal{
Dog(){
[Link]("dog is created");
}
}
class TestSuper4{
public static void main(String args[]){
Dog d=new Dog();
}}

Output:

animal is created
dog is created

super example: real use

Let's see the real use of super keyword. Here, Emp class inherits Person class so all the
properties of Person will be inherited to Emp by default. To initialize all the property, we
are using parent class constructor from child class. In such way, we are reusing the parent
class constructor.

class Person{
int id;
String name;
Person(int id,String name){
[Link]=id;
[Link]=name;
}
}
class Emp extends Person{
float salary;
Emp(int id,String name,float salary){
super(id,name);//reusing parent constructor
[Link]=salary;
}
void display(){[Link](id+" "+name+" "+salary);
}
}
class TestSuper5{
public static void main(String[] args){
Emp e1=new Emp(1,"ankit",45000f);
[Link]();
}}

Output:

1 ankit 45000

2.3. Method Overriding in Java


1.​ Understanding the problem without method overriding
2.​ Can we override the static method
3.​ Method overloading vs. 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 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.

Usage of Java Method Overriding

o​ Method overriding is used to provide the specific implementation of a method which


is already provided by its superclass.
o​ Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1.​ The method must have the same name as in the parent class
2.​ The method must have the same parameter as in the parent class.
3.​ There must be an IS-A relationship (inheritance).
Understanding the problem without method overriding

Let's understand the problem that we may face in the program if we don't use method
overriding.

//Java Program to demonstrate why we need method overriding


//Here, we are calling the method of parent class with child
//class object.
//Creating a parent class
class Vehicle{
void run(){[Link]("Vehicle is running");}
}
//Creating a child class
class Bike extends Vehicle{
public static void main(String args[]){
//creating an instance of child class
Bike obj = new Bike();
//calling the method with child class instance
[Link]();
}
}

Vehicle is running

Problem is that I have to provide a specific implementation of run() method in subclass that
is why we use method overriding.

Example of method overriding

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.

//Java Program to illustrate the use of Java Method Overriding


//Creating a parent class.
class Vehicle{
//defining a method
void run(){[Link]("Vehicle is running");}
}
//Creating a child class
class Bike2 extends Vehicle{
//defining the same method as in the parent class
void run(){[Link]("Bike is running safely");}

public static void main(String args[]){


Bike2 obj = new Bike2();//creating object
[Link]();//calling method
}
}
Output:

Bike is running safely

A real example of Java Method Overriding

Consider a scenario where Bank is a class that provides functionality to get the rate of
interest. However, the rate of interest varies according to banks. For example, SBI, ICICI and
AXIS banks could provide 8%, 7%, and 9% rate of interest.

Java method overriding is mostly used in Runtime Polymorphism which we will learn in
next pages.
//Java Program to demonstrate the real scenario of Java Method Overriding
//where three classes are overriding the method of a parent class.
//Creating a parent class.
class Bank{
int getRateOfInterest(){return 0;}
}
//Creating child classes.
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
class ICICI extends Bank{
int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
//Test class to create objects and call the methods
class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
[Link]("SBI Rate of Interest: "+[Link]());
[Link]("ICICI Rate of Interest: "+[Link]());
[Link]("AXIS Rate of Interest: "+[Link]());
}
}

Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

Can we override static method?

No, a static method cannot be overridden. It can be proved by runtime


polymorphism, so we will learn it later.

Why can we not override static method?

It is because the static method is bound with class whereas instance method is
bound with an object. Static belongs to the class area, and an instance belongs to the
heap area.

Can we override java main method?

No, because the main is a static method.

Difference between method overloading and method overriding in java

There are many differences between method overloading and method overriding in java. A
list of differences between method overloading and method overriding are given below:

No. Method Overloading Method Overriding

1) Method overloading is used to increase the Method overriding is used to provide


readability of the program. the specific implementation of the
method that is already provided by its
super class.

2) Method overloading is performed within class. Method overriding occurs in two


classes that have IS-A (inheritance)
relationship.

3) In case of method overloading, parameter must be In case of method


different. overriding, parameter must be same.

4) Method overloading is the example of compile time Method overriding is the example
polymorphism. of run time polymorphism.

5) In java, method overloading can't be performed by Return type must be same or


changing return type of the method only. Return covariant in method overriding.
type can be same or different in method
overloading. But you must have to change the
parameter.

2.4 Dynamic Method Dispatch

Dynamic method dispatch or run-time polymorphism is the mechanism through which the
correct version of an overridden method is called at runtime. When a subclass overrides a
method from its superclass, the overridden method in the subclass is executed when called
on an instance of the subclass, even if the reference to the object is of the superclass type.

In the previous example, when we call [Link]() in the loop, the appropriate
makeSound() method defined in either Dog or Cat is executed based on the actual type of
the object.

It is a powerful feature because it allows for flexibility in the way we write code. We can
write methods in the superclass that are common to all subclasses, and then have specific
behavior defined in each subclass.

Use Cases for Dynamic Method Dispatch

Dynamic method dispatch is particularly useful in scenarios where we want to write code
that operates on a general type but can be specialized by subclasses. It promotes code
reusability and allows for cleaner and more modular code.

For example, if we were building a game with different types of characters (for example,
warriors, mages, archers), we could have a Character superclass with the attack() method.
Each specific character type (warrior, mage, archer) would then override the attack()
method with its own implementation. It allows us to write code that can handle any type of
character without knowing the specific details of how each one attacks.

Complete Java program that demonstrates dynamic method dispatch along with input and
output.

[Link]

class Animal {
void makeSound() {
[Link]("Generic Animal Sound");
}
}
class Dog extends Animal {
@Override
void makeSound() {
[Link]("Bark");
}
}
class Cat extends Animal {
@Override
void makeSound() {
[Link]("Meow");
}
}
public class DynamicMethod {
public static void main(String[] args) {
Animal[] animals = {new Dog(), new Cat()};
for (Animal animal : animals) {
[Link]();
}
}
}

Output:

Bark
Meow

In the Main class, we have created an array of Animal objects called animals and populate it
with an instance of Dog and an instance of Cat. We then iterate through the animals array
using a for-each loop and call the makeSound() method on each element. Due to dynamic
method dispatch, the appropriate version of makeSound() from either Dog or Cat will be
executed based on the actual type of the object.

Dynamic method dispatch is a powerful feature of Java that enables polymorphism and
promotes code reusability and modularity. By allowing objects to take on multiple forms,
Java provides a flexible and extensible platform for building complex applications.

Understanding dynamic method dispatch is essential for writing efficient and maintainable
code in Java, especially in scenarios where you want to work with objects at a higher level
of abstraction. It is a fundamental concept in object-oriented programming that every Java
developer should master.

2.5. ABSTRACT CLASS AND METHODS


A class which is declared with the abstract keyword is known as an abstract class in Java.
It can have abstract and non-abstract methods (method with the body). It needs to be
extended and its method implemented. It cannot be instantiated.

Rules for Abstract Class


​ An abstract class must be declared with an abstract keyword.
​ It can have abstract and non-abstract methods.
​ It cannot be instantiated.
​ It can have constructors and static methods also.
​ It can have final methods which will force the subclass not to change the body of the
method.

Syntax

abstract class classname


{
---
---
}
Abstract Method in Java

​ A method which is declared as abstract and does not have implementation is


known as an abstract method.

abstract void printStatus();//no method body and abstract

​ Mostly, we don't know about the implementation class (which is hidden to the end
user), ​and an object of the implementation class is provided by the factory method.

​ A factory method is a method that returns the instance of the class. We will learn
about ​the factory method later.

For example, In java program we have formed three classes.

✔​ class A is a base class consists of two methods namely fun1() and fun2(),

✔​ The class B and class C are derived from class A


✔​ The class A is an abstract class since it contains one abstract method fun1().

✔​ We have defined this method as abstract because, its definition of fun1() is


overridden in the derived classes B and C. An another function of class A that is
fun2() is a regular function.

Example1:Abstract Class and Methods

abstract class A //abstract class


{

abstract void fun1(); //abstract method


void fun2() //normal method
{
[Link]( A:In fun2 ):
}

class B extends A
{

void fun1()​ //function overridden from abstract class


{

[Link]( B:In fun1 );


}

}
class C extends A
{

void fun1()​ //function overridden from abstract class


{
[Link]( C:In fun1 );

}
}

public class AbstractClsDemo


{

public static void main(String args[])


{

B b=new B();
C c=new C();

b.fun1();
b.fun2();

c.fun1();
c.fun2();
}

Output:

B:In fun1
A:In fun2

C:In fun1
A:In fun2

Example2:

abstract class Base


{

abstract void fun();


}
class Derived extends Base

{
void fun()

{
[Link]( Derived fun() called );
}

}
class Main()

{
public static void main(String args[])

{
Base b=new Derived();

[Link]();
}

}
Output:

Derived fun() called

[Link] CLASS AND METHODS


The final keyword in java is used to restrict the user.
The final keyword can be used in three places

​ For declaring variables

​ For declaring the methods


​ For declaring the class

Final Variables and Methods

If you make any variable as final, you cannot change the value of final variable. The
final variable is constant always.

final datatype variablename = value;

For example:
final int a=10;

The final keyword can also be useful to the method. The method using final keyword cannot
be overridden.

Java program which makes use of the keyword final for declaring the method

class B{
final int i=90;//final variable
void run(){
i=400;
}
public static void main(String args[]){
B obj=new B();
[Link]();
}
}//end of class

Output:

Compile by: javac [Link]

[Link]: error: cannot assign a value to final variable i​


i=400;​
^​
1 error

Java final method

If you make any method as final, you cannot override it.

Java program which makes use of the keyword final for declaring the method
class Test

{
final void fun() //final keyword used in method
{

[Link]( Hello,this function declared using final );


}

}
class Test1 extends Test

{
final void fun()

{
[Link]( Hello,this function declared using final );

}
}

Output:

[Link]:fun() in Test1 cannot override fun() in Test;overridden method


is final final void cun()

1 error
Example mentioned above, on execution shows the error. since fun method is declared with
the keyword final and it cannot be overridden in sub class.

Final Class

If we declare specific class as final, no class can be derived from it.

Example1:Final Class

final class Test

{
void fun()

{
[Link]( This is the function of base class );
}

class Test1 extends Test

final void fun()

{
[Link]( This is the function of derived class );

}
}

Output:

[Link] :cannot inherit from final Test


class Test1 extends Test

1 error

Example2:Final Class
class point

{
intx,y;
}

classColoredPoint extends Point

{
int color;

}
final class Colored3dPoint extends ColoredPoint
{

int z;
}

Class FinalClassDemo

{
public static void main(String args[])
{

Colored3dPoint cObj=new Colored3dPoint();


cObj.z=10;

[Link]=1;
cObj.x=5;

cObj.y=8;
[Link]( x= +cObj,x);

[Link]( y= +cObj,y);
[Link]( z= +cObj,z);

[Link]( Color= +cObj,color);

}
}

Output:
x=5

y=8
z=10

Color=1

2.7. The Object class

Object class is a special class in [Link] no inheritance is precise for the classes then all
those classes are derived class of the Object class. We can consider ,Object is a
superclass of all other classes by default. therefore

Public class A{……}is equal to public class A extends Object{……}

A reference variable of type Object can refer to any object of additional classes.

The package [Link] includes below specified method


Method Purpose
Object clone() Creates a new object that is similar to object being cloned

Boolean Concludes whether one object is similar to another


equals(Object
object)
void finalize() Called by an unused object is used again
class getclass() Holds the class of an object at run time
inthashcode() Returns the hash code associated with the invoking object
void notify() Resumes execution of a thread waiting on the invoking object
void notifyall() Resumes execution of all threads waiting on the invoking objecg
String toString() Returns a string that describes the object
void Waits on another thread of execution
wait()
Void wait(long
milliseconds)
Void wait(long
milliseconds,int
nanoseconds)

toString() Method of Object Class

​ The toString function returns the string type value.


​ The syntax is
​ ​ public String toString()

If we call up the toString method, by default then it gives a string which describes the
object. This returned string contains the character @ and object s memory address in
hexadecimal form.

We can identify with the idea of toString() method by using as it is and overriding it with
appropriate string.

Example:Illustration1
class A extends Object

{
}

class B extends A
{

}
class ObjectClassDemo

{
public static void main(String args[])

{
A obj=new A();

[Link]( Obj: +obj);


[Link]( [Link](): +[Link]());

}
}

Output:
obj:A@3e25a5

[Link]():A@3e25a5

Example:Illustration
class A extends Object

{
public String toString()
//method is overriden
{
String str= Hello ;

return str;
}

}
class B extends A

{
}

class ObjectClassDemo
{

public static void main(String args[])


{

A obj=new A();
[Link]( Obj: +obj);

[Link]( [Link](): +[Link]());


}
}

Output:

Obj:Hello
[Link]():Hello

Example2:

Import [Link].*;
class StringDemo
{
public static void main(String args[])

{
Point c=new Point(10,20);​ //Explicitly call toString() on object as part of string
concatenation

[Link]( C= +[Link]()); //Using the default [Link]() method


[Link]( C= +c);​ //Implicitly call toString() on object as part of string
concatenation
String s=c+ testing ;

[Link](s);
}

Output:
C=[Link][x=10,y=20]

C=[Link][x=10,y=20]
[Link][x=10,y=20] testing

Equals method of Object class

The method equals is helpful for comparing values given by two objects.

Example1:
class A extends Object
{

int a=10;
public Boolean equals(Object obj)

{
if(obj instanceof B)
{

return a==((B)obj).b;
}

else
return false;

}
}
class B extends A

{
int b=10;
}
class ObjectClassDemo1

{
public static void main(String args[])
{

A obj1=new A();
B obj2=new B();

[Link]( The two values of a and b are equal: +[Link](obj2));


}
}

Output:

The two values of a and b are equal:true

2.8. INNER CLASSES

Inner classes are the nested classes. We can simply represent that are defined inside the
other [Link] below syntax defining the inner class is

Access_modifier class outerClass


{
//code
Access_modifier class InnerClass
{//code
}
}

Advantage of Java inner classes

1.​ Nested classes represent a particular type of relationship that is it can access all the
members (data members and methods) of the outer class, including private.
2.​ Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.
3.​ Code Optimization: It requires less code to write.

Types of Nested classes

There are two types of nested classes non-static and static nested classes. The non-static
nested classes are also known as inner classes.

o​ Non-static nested class (inner class)


1.​ Member inner class
2.​ Anonymous inner class
3.​ Local inner class
o​ Static nested class

[Link] member classes


​ A static class is a class that is created inside a class, is called a static nested class in
Java. It cannot access non-static data members and methods. It can be accessed by
outer class name.
​ It can access static data members of the outer class, including private.
​ The static nested class cannot access non-static (instance) data members

Syntax:

Access_modifier class OuterClass


{
//Code
public static class InnerClass
{
//Code
}
}

Java static nested class example with instance method


[Link]
class TestOuter1{
static int data=30;
static class Inner{
void msg()
{
[Link]("data is "+data);
}
}
public static void main(String args[])
{
[Link] obj=new [Link]();
[Link]();
}
}

[Link] classes
A class created within class and outside method. It is also known as a regular inner
class. It can be declared with access modifiers like public, default, private, and
protected.

Syntax:

class Outer{
//code
class Inner
{
//code
}
}

Example

we are creating a msg() method in the member inner class that is accessing the private data
member of the outer class.

[Link]
class TestMemberOuter1{
private int data=30;
class Inner{
void msg(){[Link]("data is "+data);}
}
public static void main(String args[]){
TestMemberOuter1 obj=new TestMemberOuter1();
[Link] in=[Link] Inner();
[Link]();
}
}

[Link] classes

​ A class was created within the method.


​ Local Inner Classes are the inner classes that are defined inside a block.

Syntax:

Access_modifier class OuterClass


{
//Code
Access_modifier return_type methodname(arguments)
{
Class Innerclass
{
//Code
}
//Code
}

[Link]
public class localInner1{
private int data=30;//instance variable
void display(){
class Local{
void msg(){[Link](data);}
}

Local l=new Local();


[Link]();
}
public static void main(String args[]){
localInner1 obj=new localInner1();
[Link]();
}
}

[Link] classes

A class created for implementing an interface or extending class. The java compiler decides
its name

It should be used if you have to override a method of class or interface. Java Anonymous
inner class can be created in two ways:

1.​ Class (may be abstract or concrete).


2.​ Interface

[Link]
abstract class Person{
abstract void eat();
}
class TestAnonymousInner
{
public static void main(String args[])
{
Person p=new Person(){
void eat(){[Link]("nice fruits");}
};
[Link]();
}
}

Output:
nice fruits
✔​ A class is created, but its name is decided by the compiler, which extends the Person
class and provides the implementation of the eat() method.
✔​ An object of the Anonymous class is created that is referred to by 'p,' a reference
variable of Person type.

Java anonymous inner class example using interface


interface Eatable{
void eat();
}
class TestAnnonymousInner1{
public static void main(String args[]){
Eatable e=new Eatable(){
public void eat(){[Link]("nice fruits");}
};
[Link]();
}
}

​PACKAGES

●​ Grouping mixture of classes and/or interfacescollectively


●​ Grouping is generally done according tofunctionality
●​ Packages act as containers forclasses

Types:
1.​ Java APIpackages
2.​ User definedpackages

Java API Packages


●​ Java API provides a large number of classes integrated in to
variouspackages according tofunctionality

Package Name Content


[Link][Primitive types, Strings, Language Support class
Mathfunctions, Threads]
[Link][vectors,hashtables,randomn Language utility classes
umbers,date]
[Link] [input & output] Input/output support classes
[Link][windows,buttons,lists,menus] Set of classes for implementing GUI
[Link] Classes for networking
[Link] Classes for creating and implementing
applets

Using System Packages


There are 2 ways of accessing the classes available in a package
1.​ First Approach : fully
qualifiedname
[Link];
●​ Imports the color class & class name can now be openly used in theprogram.
2.​ Second Approach: Once or when we do not want to access any other classes of
the package
●​ bring all the classes of [Link].

Use a class in number of times in a program/like to use different classes enclosed in a


package.
import [Link];
or
import packagename.*;

Naming Conventions
Can be named using standard naming rules
1.​ packages start with lowercaseletters.
2.​ class names start with uppercaseletters.
3.​ Methods start with lowercase
letters. Ex: double
y=[Link](x)
[Link] :package
Math: class name
sqrt: method name.

Benefits of Packages
●​ The classes enclosed in the packages of other programs can be simplyreused
●​ They give a way to “hide” classes thus preventing from new programs orpackages
●​ Also supply a way for separating “design” from“coding”
●​ Two different classes in 2 various packages can have similarname.
Java user defined package
Creating a user defined Package
●​ First declare the package name using the package keyword continued by a
package name
●​ This must be the initial statement in a java sourcefile.
●​ Then you can define a class just as we usually define aclass

package firstpackage;//package
declaration public class Firstclass//class
definition
{
Body
}

Creating our own package or user defined packages follows the following steps
1.​ Declare the package at the
starting of a file
packagepackagename;
2.​ Define the class that is to be place in the package & declare itpublic.
3.​ Create a subdirectory below the directory where the main source files arestored
4.​ Keep the listing as the [Link] file in the subdirectorycreated
5.​ Compile the [Link] generates class file in thesubdirectory.
●​ Java also provides the concept of packagehierarchy
●​ This is done by specifying many names in a package statement,separated bydots.
package [Link];

Accessing a Package
●​ In java programming package can be accessed either using a fully qualified class
name or using another shortcut method through the importstatement.
●​ The general form of importstatement
import package1[.package2][.package3].classname;
●​ The system must end with asemicolon(;)
●​ The import statement should become visible before any class definitions in a
source file.
`​ Ex:
Importing a particular class
import [Link];
●​ After defining, all the fields of the class Myclass can be straightly accessed using
the class name or its objects can be used directly without specifying the
packagename.

Ex: import packagename.*;

●​ May denote a single package or a hierarchy of packages. * represents that the


compiler should look for this whole hierarchy when it encounters a classname

Example:
package
package1;
public class
ClassA
{
public void displayA()
{
[Link](“Class A”);
}
}

import
[Link];
class Test
{
public static void main(String args[])
{
ClassAobjectA=new
ClassA();
[Link]();
}
}
output :

ClassA

Example
package
package2; public
class ClassB
{
protected int m=10;
public void display()
{
[Link](“Class
B”);
[Link](“m=”+
m);
}
}

Example:
import
[Link];
import package2.*;
class Test2
{
public static void main(String args[])
{
ClassAobjA=new
ClassA();
ClassBobjB=new
ClassB();
[Link]();
[Link]();
}
}
}

Output:

Class A
Class B
M =10

Example
import [Link];
class ClassC extends
ClassB
{
int n=20;
void displayC()
{
[Link](“Class
C”);
[Link](“m=”
+m);
[Link](“n=”+
n);
}
}

class Test2
{
public static void main(String args[])
{
ClassCobjC=new
ClassC();
[Link]();
[Link]();
}
}

OUTPUT: Class B
M=10
Class C
m=10 n=20

2.5. INTERFACES

​ Java does not support multiple inheritance.


​ Classes in java cannot have more than one base class.

​ Java gives an alternate method known as interfaces to implement the concept of


multiple inheritance.
​ Java Interface also represents the IS-A relationship.
​ It cannot be instantiated just like the abstract class.
​ Since Java 8, we can have default and static methods in an interface.
​ Since Java 9, we can have private methods in an interface.

Why use Java interface?


There are mainly three reasons to use interface. They are given below.
o​ It is used to achieve abstraction.
o​ By interface, we can support the functionality of multiple inheritance.
o​ It can be used to achieve loose coupling.

[Link] interfaces
It is a type of a class but cannot be instantiated the new operator. Like classes, interface will
have functions and variables but with a most important difference Interfaces can have only
abstract functions and final members. It won t be instantiated/implemented or extended.
This means that interfaces do not identify any code to execute these functions and data
members have only constants. Therefore, it is the duty of the class that implements an
interface to develop the code for implementation of such functions

Syntax:
interface interfacename
{
Variables declaration;
Methods declaration;
}

In other words, Interface fields are public, static and final by default, and the
methods are public and abstract.

returntype methodname(parameter_list)

Example1:
interface Item

{
static final int code=100;

static final String name=fun;


void display();

}
Example2:

interface Area
{

final static float pi=3.14F;


float compute(float x,float y);

void show();
}
The relationship between classes and interfaces

As shown in the figure given below, a class extends another class, an interface extends
another interface, but a class implements an interface.

[Link] interfaces

Interfaces can be consider as base class. Properties are inherited by classes.

Syntax:
class classname implements interfacename
{
body of class
}

classclassname extends superclass implements interface ,interface …


{
body of class
}

Example program1:
interface Area

{
final static float pi=3.14F;

float compute(float x,float y);


}
class Rectangle implements Area
{

public float compute(float x,float y)


{

return(x*y);
}

class Circle implements Area


{

public float compute(float x,float y)


{

return(pi*x*x);
}
}

class interfacetest

{
public static void main(String args[])

{
Rectangle rect=new Rectangle();

Circle cr=new Circle();


Area area;

area=rect;

[Link]( Area of Rectangle: +[Link](10,20));


Area=cir;

[Link]( Area of Circle: +[Link](10,0));

}
}

Output:
Area of Rectangle:200

Area of Circle:314

Implementing multiple and Hybrid inheritance

class student
{
int rollno;

void getno(int no)


{

Rollno=no;
}

Void putno()
{
[Link]( Rollno: +rollno);

}
}

class Test extends student

{
float mark1,mark2;

void getmarks(float m1,float m2)


{

mark1=m1;
mark2=m2;

}
void putmarks()

{
[Link]( Mark1: +mark1);
[Link]( Mark2: +mark2);

}
}

interface sports

{
floatsportwt=6.0F;

voidputwt();
}

class Results extends test implements sports

{
float total;

public void putwt()


{
[Link]( Sportswt: +sportwt);

}
void display()

{
total=mark1+mark2;

putno();
putmarks();

putwt();
[Link]( Total Score: +total);
}

class Hybrid
{

public static void main(String args[])


{

Results s1=new Results();


[Link](100);

[Link](50.0F,50.F);
[Link]();

}
}

Output:
Rollno:100
Mark1:50.0

Mark2:50.0
Sportswt:6.0

Total Score:100.0

Example2:
interface interface1

{
public void show_val();

class Base
{
int val;
public void set_val(int i)
{

val=i;
}

class A extends Base implements interface1


{

public void show_val()


{

[Link]( The value of a= +val);


}

}
class B extends Base implements interface1
{
public void show_val()

{
[Link]( The value of b= +val*5);

}
}

class multipleinherit
{

public static void main(String args[])


{interface1 obj_A=new A();
interface1 obj_B=new B();

obj_A.set_val(10);
obj_B.set_val(20);

obj_A.show_val();
obj_B.show_val();

}}

Output:
The value of a=10
The value of b=100

Multiple inheritance in Java by interface


If a class implements multiple interfaces, or an interface extends multiple interfaces, it is
known as multiple inheritance.
[Link] between class and interface
Class Interface
The class is represented by a keyword class The interface is represented by a keyword
interface
The class consists data members and The interfaces may have data members and
[Link] the methods are defined in methods but the methods will not be
class
[Link] consists ofan [Link] interface serves as an
class summarize
executable code for the class
With the help of instance of a class ,class Not possible to create an instance of an
members can be accessed instance
The class can use different access specifiers The interface will use only public access
like public,private or protected specifier
The data members of a class can be The data members of interfaces are
constant constantly
or final declared as final

[Link] between abstract class and interface


.
Abstract Class Interface
The new class can inherit only one abstract The class can implement more than one
class interfaces
Members of abstract class can have any Members of interface are public by default
access
modifier such as public,private and
protected.
The methods in abstract class may or may The methods in interface have no
not
have implementation implementation at [Link] declaration of
the
methods is given
Java abstract classes are comparatively The interfaces are comparatively slow and
Efficient implies extra level of indirection
Java abstract class is extended using the Java interface can be implemented by using
keyword abstract the keyword implements
The member variables of abstract class can The member variables of interface are by
be
non final default final

[Link] interfaces

One interface can able to extend with another one interfaces

The sub interface will take over all the data members of the base interface using
extends keyword

Syntax:

interface name2 extends name1


{

body of name2
}
2 MARK QUESTIONS AND ANSWERS

1. Define Inheritance. May/June 2012

Inheritance can be defined as the process where one object acquires the properties of
another. With the use of inheritance the information is made manageable in a hierarchical
[Link] resulting classes are known as derived classes, subclasses, or child classes. Older
class is known as super class.

[Link] are the conditions to be satisfied while declaring abstract classes

Java Abstract classes are used to declare common characteristics of subclasses. An abstract
class cannot be instantiated. It can only be used as a superclass for other classes that extend
the abstract class. Abstractclasses are declared with the abstract keyword. Abstract classes
are used to provide a template or design for concrete subclasses down the inheritance tree.

3. You can create an abstract class that contains only abstract methods. On the other

hand, you can create an interface that declares the same methods. So can you use
abstract classes instead of interfaces?

Sometimes. But your class may be a descendent of another class and in this case the
interface is your only option

4. Explain the concept of Polymorphism.

Polymorphism means when an entity behaves differently depending upon the context its
being used. Moreover In other words Polymorphism is the capability of an action or method
to do different things based on the object that it is acting upon. Means polymorphism
allows you define one interface and have multiple implementations. That being one of the
basic principles of object oriented programming.

5. Explain about Virtual methods.

A child class can override a method in its parent. An overridden method is essentially
hidden in the parent class, and is not invoked unless the child class uses the super keyword
within the overriding method.

6. What is Static Binding?

Connecting a method call(i.e. Function Call) to a method body(i.e. Function) is called


binding. When binding is performed before the program is run (by the compiler and linker,
if there is one), it s called early binding or static Binding.

7. What is Dynamic binding?

The runtime system [JVM]during runtime determines the appropriate method call based on
the class of the object. This feature is called as Polymorphism. All the methods in java are
dynamically resolved. This cannot be determined by the Compiler.
8. What is an Abstract classes and Methods?

An abstract method is a method that is declared without an implementation (without


braces, and followed by a semicolon), like this:

abstract void moveTo(double deltaX, double deltaY);


If a class includes abstract methods, the class itself must be declared abstract, as in:

public abstract class GraphicObject {


//​declare fields

//​ declare non-abstract


methods abstract void
draw();

When an abstract class is subclassed, the subclass usually provides implementations for all
of the abstract methods in its parent class. However, if it does not, the subclass must also be
declared abstract.

9. With example Explain Abstract Classes?

First, you declare an abstract class, GraphicObject, to provide member variables and
methods that are wholly shared by all subclasses, such as the current position and the
moveTo method. GraphicObject also declares abstract methods for methods, such as draw
or resize, that need to be implemented by all subclasses but must be implemented in
different ways.

10. When an Abstract Class Implements an Interface?

It was noted that a class that implements an interface must implement all of the interface's
methods. It is possible, however, to define a class that does not implement all of the
interface methods, provided that the class is declared to be abstract. For example, abstract
class X implements Y {

//​implements all but one method of Y


}

class XX extends X {
//​implements the remaining method in Y
}

In this case, class X must be abstract because it does not fully implement Y, but class XX
does, in fact, implement Y.

11. What is Object Class?

The Object class defines the basic state and behavior that all objects must have, such as the
ability to compare oneself to another object, to convert to a string, to wait on a condition
variable, to notify other objects that a condition variable has changed, and to return the
object's class.

12. What is an interface (Nov/Dec 2011)

An interface is a collection of method definitions (without implementations) and constant


values. In Java, an interface is a reference data type and, as such, can be used in many of the
same places where a type can be used (such as in method arguments and variable
declarations)

13.​What are the uses of Interfaces?(Nov/Dec2010)


​ Capturing similarities between unrelated classes without forcing a class
relationship.

​ Declaring methods that one or more classes are expected to implement.

​ Revealing an object's programming interface without revealing its class. (Objects


such as these are called anonymous objects and can be useful when shipping a
package of classes to other developers.)

14.​Why Interfaces Do not Provide Multiple Inheritances?


​ You cannot inherit variables from an interface.

​ You cannot inherit method implementations from an interface.

​ The interface hierarchy is independent of a class hierarchy--classes that implement


the same interface may or may not be related through the class hierarchy. This is not
true for multiple inheritances.

15.​What is meant by Reflection API?

Reflection is commonly used by programs which require the ability to examine or modify
the runtime behavior of applications running in the Java virtual machine. This is a relatively
advanced feature and should be used only by developers who have a strong grasp of the
fundamentals of the language.

16.​ What are the uses of


Reflection? Extensibility
Features
An application may make use of external, user-defined classes by creating instances of
extensibility objects using their fully-qualified names.

Class Browsers and Visual Development Environments

A class browser needs to be able to enumerate the members of classes. Visual development
environments can benefit from making use of type information available in reflection to aid
the developer in writing correct code.

Debuggers and Test Tools

Debuggers need to be able to examine private members on classes. Test harnesses can
make use of reflection to systematically call a discoverable set APIs defined on a class, to
insure a high level of code coverage in a test suite.

17.​What are the Drawbacks of Reflection?

Reflection is powerful, but should not be used indiscriminately. If it is possible to perform


an operation without using reflection, then it is preferable to avoid using it. The following
concerns should be kept in mind when accessing code via reflection.

​ Performance Overhead
​ Security Restrictions

​ Exposure of Internals

18.​What is object cloning in Java? (May/June 2013)

Objects in Java are referred using reference types, and there is no direct way to copy the
contents of an object into a new object. The assignment of one reference to another merely
creates another reference to the same object. Therefore, a special clone() method exists for
all reference types in order to provide a standard mechanism for an object to make a copy
of itself. Here are the details you need to know about cloning Java objects.

[Link] Inner classes. (Apr/May 2011)

​ An inner class is a class that is defined inside another class

​ Inner class methods can access the data from the scope in which they are defined
including data that would otherwise be private.
​ Inner classes can be hidden from other classes in the same package.


20.​What are the properties of proxy class ?
•​ Proxy classes are created on the fly in the running program.

•​ Once they are created they are just like any other class in the V.M.

•​ All proxy classes extends the class proxy.


•​ A proxy class as only one instant field. The innovation handles which is defined
in the proxy super class.

21.​ What​ is​ final​ modifier?(May/June​ 2013)


The final modifier keyword makes the programmer cannot change the value anymore.
that The
actual meaning depends on whether it is applied to a class, a variable, or a method.
final Classes A final class canno have subclasses.
- t
final Variables- A final variable cannot be change once it is initialized.
d

final Methods- A final method cannot be overridden by subclasses.

21.​Explain about Java I/OPackage?


The Java I/O Package ([Link]) provides a set of input and output streams used to read
and write data to files or other input and output sources. The classes and interfaces
defined in [Link] are covered fully in Input and Output Streams.

22.​Explain about Java UtilityPackage?


This Java package, [Link], contains a collection of utility classes. Among them are
several generic data structures (Dictionary, Stack, Vector, Hashtable) a useful object for
tokenizing a string and another for manipulating calendar dates. The [Link] package
also contains the Observer interface and Observable class, which allow objects to notify
one another when they change. The [Link] classes aren't covered separately in this
tutorial although some examples use theseclasses.

23.​Explain about AppletPackage?


This package contains the Applet class -- the class that you must subclass if you're
writing an applet. Included in this package is the AudioClip interface which provides a
very high level abstraction of audio. Writing Applets explains the ins and outs of
developing your ownapplets.

24.​Explain about the JavaPackages?(NOV/DEC2010)


Several packages of reusable classes are shipped as part of the Java development
environment. Indeed, you have already encountered several classes that are members
of these packages: String, System, and Date, to name a few. The classes and interfaces
contained in the Java packages implement various functions ranging from networking
and security to graphical user interface elements.

PART B -13 MARK QUESTIONS


1.​Explain the concept of inheritance and its types.
2.​Explain the concept of overriding with examples.
3.​What is dynamic binding? Explain with example.

4.​Explain the uses of reflection with examples.


5.​Define an interface. Explain with example.

6.​Explain the methods under object class and class class.


7.​What is object cloning? Explain deep copy and shallow copy with examples.

8.​Explain static nested class and inner class with examples.


9.​With an example explain proxies.

10.​ Develop a message abstract class which contains playMessage abstract method.
Write a different sub-classes like TextMessage, VoiceMessage and FaxMessage classes for to
implementing the playMessage method.

11.​ Develop a abstract Reservation class which has Reserve abstract method. Implement
the sub-classes like ReserveTrain and ReserveBus classes and implement the same.

12.​ Develop an Interest interface which contains simpleInterest and compInterest


methods and static final field of Rate 25%. Write a class to implement those methods.

13.​ Develop a Library interface which has drawbook(), returnbook() (with fine),
checkstatus() and reservebook() methods. All the methods tagged with public.

14.​ Develop an Employee class which implements the Comparable and Cloneable
interfaces. Implement the sorting of persons (based on name in alphabetical). Also
implement the shallow copy (for name and age) and deep copy (for DateOfJoining).

15.​Explain the different methods supported in Object class with example.


16.​Explain Packages indetail.

Part-C 15 MARK QUESTIONS

1.​ Develop a static Inner class called Pair which has MinMax method for finding min
and max values from the array.

2.​Explain the following with examples(NOV/DEC 2010)


i.​ The clone able interface(8)

ii.​ The property interface. (7)


[Link] an application using inheritance and interfaces
[Link] a book application and apply various string operations to find particular string.

[Link] the help of real time application explain object cloning in java.
[Link] some of the classes available under Lang package and develop your own applications..

You might also like