Unit-II
Inheritance in Java:
Inheritance is one of the three foundation principles of object oriented programming because it allows the creation of hierarchical classification. Using
inheritance, a user can create a general class that defines a set of related items. This class can then be inherited by other, more specific classes, each adding those
things that are unique to it.
Java supports Inheritance by allowing one class to incorporate another class into its declaration. This is done by using the extends keyword. That
means the subclass adds to the superclass. Let’s start with a small example program that illustrates several key features of inheritance. The following program
creates a superclass called TwoDShape, which stores the width and height of a two dimensional object, and a subclass called Triangle. Notice how the keyword
extends is used to create a subclass.
class TwoDShape
{
double width;
double height;
void showDim ()
{
[Link] ("width and height are" +width +" and “+height);
}
}
class Triangle extends TwoDShape
{
String style;
double area ()
{
return (width*height)/2;
}
void showStyle()
{
[Link] ("Triangle is" + style);
}
}
public class Shapes {
public static void main (String[] args)
{
Triangle t1=new Triangle ();
Triangle t2=new Triangle ();
[Link]=4.0;
[Link]=4.0;
[Link]="filled";
[Link]=8.0;
[Link]=12.0;
[Link]="outlined";
[Link] ("info for t1:");
[Link] ();
[Link] ();
[Link] ("Area is" +[Link] ());
[Link] ();
[Link] ("info for t2:");
[Link] ();
[Link] ();
[Link] ("Area is" +[Link] ());
}}
Output:
Info for t1:
Triangle is filled
Width and height are4.0 and 4.0
Area is8.0
Info for t2:
Triangle is outlined
Width and height are8.0 and 12.0
Area is48.0
Hierarchies:
In Java, an inheritance hierarchy refers to the structured relationship between classes where a class (subclass or child class) inherits properties and behaviours
from another class (superclass or parent class). This creates a tree-like structure, with the [Link] class at the very top as the root of all class hierarchies
in Java.
Key aspects of the inheritance hierarchy in Java include:
Object Class as Root: Every class in Java implicitly or explicitly extends [Link]. This means that all classes ultimately inherit methods like equals
(), hashCode(), toString(), etc., from the Object class.
extends Keyword: Inheritance is established using the extends keyword. A subclass extends a superclass to inherit its non-private members (fields and methods).
Code Reusability: Inheritance promotes code reusability by allowing subclasses to leverage functionality defined in their super classes, avoiding redundant code.
Polymorphism: Inheritance is a fundamental concept for achieving polymorphism, where objects of different subclasses can be treated as objects of their
common superclass.
Types of Inheritances in Java:
In Java, Inheritance may take different forms which are given below:
Single Inheritance (only one super class)
Multiple Inheritance(several super classes)
Multi level Inheritance (Derived from a derived class)
Hierarchical Inheritance(one super class, many sub classes)
These forms of inheritance are shown in following figures. Java does not directly implement multiple inheritances. However this concept is implemented using a
secondary inheritance path in the form of Interfaces.
A
A
A B
A B
Single Inheritance
BHierarchicalDInheritanceC C C
B
Multi level Inheritance Multiple Inheritance
Defining a subclass:
A subclass is defined as follows:
class subclassname extends superclassname
{variable declaration;
methods declaration;
}
The keyword extends signifies that the properties of the superclassname are extended to the subclassname. The subclass will now contain its own variables and
methods as well those of the superclass. This kind of situation occurs when we want to add some more properties to an existing class without actually modifying
it.
The following program demonstrates the creation of superclass and subclass and also demonstrates the functionality of single inheritances.
class Room //superclass
{
int length,breadth;
Room(int x,int y) //constructor
{
length=x;
breadth=y;
}
int area()
{
return (length*breadth);
}
}
class Room1 extends Room //Room1 is a subclass
{
int height;
Room1(int x,int y,int z) //subclass constructor
{
super(x,y); //super is a keyword
height=z;
}
int volume()
{
return(length*breadth*height);
}
}
public class InherTest {
public static void main (String [] args)
{
Room1 r1=new Room1 (2,3,4); //subclass object
int a1=[Link]();
int v1=[Link]();
[Link] ("Area1= " + a1);
[Link] ("volume =" +v1);
}}
Output:
Area= 6
volume =24
In the above program Room is a superclass contains two variables such as length and breadth and one method i.e., area. Room1 is a subclass contains one
variable and one method such as height and volume respectively. The subclass Room1 takes the properties of superclass that is Room by using one keyword
such as super.
Member Access Rules in Java:
The member access rules determines whether a sub class can use a property of its super class or it can only access or it can neither access nor access. There are
two level of access control:
At the top level: public or package-private.
At the member level: public, private, and protected.
A class may be declared with the 'public' modifier; in that case that class is visible to all classes everywhere.
At the member level, there are three different access modifiers are there: 'private', 'protected' and 'public'.
private: If private access modifier is applied to an instance variable, method or with a constructor inside a class then they will be accessed inside that class only
not outside of the class.
For example:
class A
{
private int x=10;
}
class B extends A
{
int y=20;
[Link](x); //Illegal access to x ;
}
If you make any class constructor private, you can't create the instance/object of that class from outside the class.
For example:
class A
{
int x;
private A (int k) // private constructor
{
x=k;
}
}
class Test
{
public static void main (String args [])
{
A ob=new A (10); //Compile time error
}
}
protected:
If protected modifier is applied to an instance variable, method or with a constructor inside a class then they will be accessed inside the package only in which
class is present and, in in addition by a subclass in another package.
public:
The class, variable, method or a constructor with public access modifier can be accessed from anywhere.
Let’s understand the access specifier with the help of following table:
Access Modifier Within class Within package Outside package by Outside package
subclass only
private Y(yes) N N(no) N
default Y Y N N
protected Y Y Y N
public Y Y Y Y
Using super to call superclass constructors:
A subclass can call a constructor defined by its superclass by use of the following form of super.
super (parameter-list); //where super is a keyword
Here, parameter-list specifies any parameters needed by the constructor in the super class. super () must always be the first statement executed inside a subclass
constructor. The following example illustrates the use of super keyword.
class A1
{
int i;
}
class B1 extends A1
{
int i;
B1 (int a,int b)
{
super.i=a;
i=b;
}
void show ()
{
[Link] ("i in superclass:" + super.i);
[Link] ("i in subclass:" + i);
}
}
public class UseSuper {
public static void main (String [] args)
{
B1 b1=new B1 (1, 2);
[Link] ();
}}
final variables and methods:
As powerful and useful the inheritance is, sometimes we need to prevent it. Whatever is the reason in java it is easy to prevent a method from being overridden
or a class from being inherited by using the keyword final. The below simple example demonstrates the use of final keyword.
class A
{
final void meth ()
{
[Link] (“This is final method”);
}}
class B extends A
{
void meth()
{[Link] (“illegal”);
}}
Because meth () is declared as final, it cannot be overridden in B. if you attempt to do so, a compile time error will result.
Similarly you can prevent a class from being inherited by preceding its declaration with final. Declaring class as final implicitly declares all of its methods as
final too.
Here is an example of a final class:
final class A
{ // some code
}
class B extends A
{ //some code
}
As we already know, it is illegal for B to inherit A since A is declared as final.
Using final with Data Members:
final keyword can also be applied to member variables to create constants. If users precede a class variable’s name with final, its value cannot be changed
throughout the lifetime of your program. When a method which is declared by using the final keyword that method functionality cannot be altered in any way.
The basic declaration of final variables and methods in java programming as shown below:
final int size=100;
final void showStatus () {----}
Sometimes we may like to prevent a class being further subclasses for security reasons. A class that cannot be sub classed is called a final class. This is achieved
in java using the keyword final as shown below:
final class Aclass {----------}
final class Bclass extends someclass {----}
Any attempt to inherit these classes will cause an error and the compiler will not allow it. Declaring a class final prevent any unwanted extensions to the class. it
also allows the compiler to perform some optimisations when a method of a final class is invoked.
Example using final variable:
public class FinalExample
{
final int MAX_VALUE = 100;
public void displayValue()
{
final String MESSAGE = "This is a constant message.";
[Link] ("Max Value: " + MAX_VALUE);
[Link] ("Message: " + MESSAGE);
}
public static void main (String[] args) {
FinalExample example = new FinalExample ();
[Link] ();
}
}
Output:
Max Value: 100
Message: This is a constant message.
Example using final method:
class SuperClass
{
final void displayInfo() {
[Link] ("This is a final method in SuperClass.");
}
}
class SubClass extends SuperClass {
// void displayInfo () { // This would cause a compilation error as final methods cannot be overridden
// [Link] ("Attempting to override final method.");
// }
}
public class FinalExample1
{
public static void main (String [] args) {
SubClass obj = new SubClass ();
[Link] (); // Calls the final method from SuperClass
}
}
Output:
This is a final method in SuperClass.
Example using final class:
final class A
{
// some code
}
Class B extends A
{
// some code
}
Output:
Shows an error because a final class never be sub classed.
The Object class and its methods:
Java defines one special class called Object that is an implicit superclass of all other classes. In other words, all other classes subclasses of Object. This means
that a reference variable of type Object can refer to an object of any other class. Also, since arrays are implemented as classes, a variable of type Object can
also refer to an array.
Object defines the following methods, which means that they are available in every object.
Method Purpose
Object clone() Creates a new object that is same as the object being cloned.
boolean equals(Object object) Determines whether one object is equal to another.
void finalize() Called before an unused object is recycled.
int hashCode() 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 object.
void wait(milliseconds) Waits on another thread of execution.
String toString() Returns a string that describes the object.
The equals () method is used to compare two objects. It returns true if the objects are equivalent and false otherwise. The toString () method returns a string that
contains a description of the object on which it is called. Also this method is automatically called when an object is output using println ().
Polymorphism in Java:
Polymorphism in java is one of the core concepts in Object Oriented Programming (OOP) that allows objects to behave differently based on their specific class
type. The word polymorphism means having many forms and it comes from the Greek words poly (many) and morph (forms), this means one entity can take
many forms. In Java, polymorphism allows the same method or object to behave differently based on the context, especially on the project’s actual runtime class.
Key features of Polymorphism:
Multiple behaviours:
The same method can behave differently depending on the object that calls this method.
Method Overriding:
A child class (subclass) can redefine a method of its parent class (superclass).
Method Overloading:
We can define multiple methods with the same name but different parameters.
Runtime Decision:
At runtime, Java determines which method to call depending on the objects actual class.
Dynamic Binding in Java:
Binding is a mechanism creating a link between method call and method actual implementation. According to the polymorphism concept in java, object can
have many different forms. Object forms can be resolved at compile time and run time.
Dynamic binding refers to the process in which linking between method call and method implementation is resolved at run time. Dynamic binding is
also known as run time polymorphism or late binding.
class Animal1
{
public void move ()
{
[Link] ("Animals can move");
}
}
class Dog1 extends Animal1
{
public void move ()
{
[Link] ("Dogs can walk and run");
}
}
public class Tester {
public static void main (String [] args)
{
Animal1 a=new Animal1 ();
Animal1 b=new Dog1 (); //Animal reference dog object
[Link] ();
[Link] ();
}
}
Output:
Animals can move
Dogs can walk and run
In the above program, we have created two classes Animal and Dog where Dog class extends Animal class. In main () method, we are using Animal class
reference and assign it an object of Dog class to check the effect of Dynamic binding. Here b is an object with Animal reference and run the move () method.
The reason for this is, in compile time, the check is made on the reference type. However, in the run time, JVM figures out the object type and would run the
method that belongs to that particular object.
Therefore in the above example, the program will compile properly since Animal class has the method move (). Then, at the runtime, it runs the method
specific for that object.
Method Overriding in Java:
In Java, a method defined in a super class is inherited by its sub class and is used by the objects created by the sub class. Method inheritance enables us to define
and use methods repeatedly in subclasses without having to define the methods again in subclass.
However, there may be occasions when we want an object to respond to the same method but have different behaviour when that method is called.
That means, we should override the method defined in the superclass. This is possible by defining a method in the subclass that has the same name, same
arguments and same return type as a method in the superclass. Then, when that method is called, the method defined in the subclass is invoked and executed
instead of the one in superclass. This is known as overriding. The following program illustrates the concept of Method Overriding.
class Sup
{
int x;
Sup (int x)
{
this.x=x;
}
void display ()
{
[Link] ("Super x=" +x);
}
}
class Sub extends Sup
{
int y;
Sub (int x,int y)
{
super(x);
this.y=y;
}
void display ()
{
[Link] ("Super x=" +x);
[Link] ("Sub y=" +y);
}
}
public class OverrideTest {
public static void main (String [] args)
{
Sub s1=new Sub(100,200);
[Link] ();
}}
Output:
Super x=100
Sub y=200
Abstract classes and methods in Java:
In java we have seen that by making a method final we ensure that the method is not redefined in a subclass. That is, the method can never be sub classed. Java
allows us to do something that is exactly opposite to this. That is, we can indicate that a method must always be redefined in a subclass, thus making overriding
compulsory. This is done using the modifier keyword abstract in the method definition.
Example:
abstract class Shape
{
---------------------
----------------------
abstract void draw ();
----------------------
----------------------
}
When a class contains one or more abstract methods, it should also be declared abstract as shown in the example above. While using abstract classes, we must
satisfy the following conditions.
We cannot use abstract classes to instantiate objects directly. For example,
Shape s=new Shape () this statement is illegal because Shape is an abstract class.
The abstract methods of an abstract class must be defined in its subclass.
We cannot declare abstract constructors or abstract static methods.
We can define static methods in an abstract class.
If a class contains at least one abstract method then compulsory should declare a class as abstract
Below is the implementation of the abstract class:
abstract class Sunstar {
abstract void printInfo ();
}
// Abstraction performed using extends
class Employee extends Sunstar {
void printInfo ()
{
String name = "avinash";
int age = 21;
float salary = 222.2F;
[Link] (name);
[Link] (age);
[Link] (salary);
}
}
// Base class
class Base1 {
public static void main (String args [])
{
Sunstar s = new Employee ();
[Link]();
}
}
Output:
avinash
21
222.2
Interfaces
Fundamentals:
In Java, an interface defines a set of methods that will be implemented by a class. Syntactically, interfaces are similar to abstract classes, except that no method
can include a body. This means that an interface provides no implementation whatsoever of the methods it defines. Therefore, an interface simply specifies what
must be done, but not how.
Once an interface is defined, any number of classes can implement it. This makes it possible for two or more classes to provide the same functionality
even though they might do so in different ways. Furthermore one class can implement any number of interfaces. This makes it possible for a single class to
provide a wide range of well-defined functionality. To implement an interface, a class must provide bodies for the methods described by the interface. Each
class is free to determine the details of its own implementation. To implement an interface, a class must provide bodies for the methods described by the
interface.
An interface is declared by use of the interface keyword. Here is a simplified general form of an interface declaration:
access_specifier interface_name
{
return_type method_name (parameter_list);
return_type method_name (parameter_list);
-------------------------------------------------
}
Here, access specifier is either public or not used. When no access modifier is included, then default access results. Although default access is proper for many
applications. In an interface methods are declared using only their return type and signature. They are essentially, abstract methods.
Difference Between Abstract Class and Interface:
INTERFACES ABSTRACT CLASSES
Specifies a set of methods a class must implement; methods are Cannot be instantiated; contains both abstract (without
abstract by default. implementation) and concrete methods or non-abstract(with
implementation)
Methods are abstract by default; Java 8, can have default and Can have both implemented and abstract methods.
static methods.
A class can implement multiple interfaces. class can inherit from only one abstract class.
Methods and properties are implicitly public. Methods and properties can have any access modifier (public,
protected, private).
Variables are implicitly public, static, and final (constants). Can have member variables (final, non-final, static, non-static).
Defining an Interface:
An interface basically a kind of class. Like classes interfaces contains methods and variables but with a major difference. The difference is that interfaces define
only abstract methods and final variables. This means that interfaces do not specify any code to implement these methods and data fields contain only constants.
Therefore it is the responsibility of the class that implements an interface to define the code for implementation of these methods.
The syntax for defining an interface is very similar to that for defining a class. The general form of an interface definition is:
interface interface_name
{
variable declaration;
method declaration;
}
Here, interface is the keyword and interface_name is any valid java identifier or variable. The variable declaration inside the interface may take the following
form:
static final type variable_name=value;
Note that all variables are declared as constants. Methods declaration will contain only a list of methods without any body statements. Example:
return_type method_name (parameters _list);
Here is an example of an interface definition that contains two variables and one method.
interface Item
{
static final int code=1001;
static final String name=”xyz”;
void display ();
}
Note that the code for the method is not included in the interface and the method declaration simply ends with a semicolon. The class that implements this
interface must define the code for the method. Another example of an interface is:
interface Area
{
final static float pi=3.14f;
float compute (float x, float y);
void show ();
}
Extending Interfaces:
Like classes, interfaces can also be extended. That is, an interface can be sub interfaced from other interfaces. The new sub interface will inherit all the members
of the super interface in the manner similar to subclasses. This is achieved using the keyword extends as shown below:
interface name2 extends name1
{
Body of name2;
}
For example, we can put all the constants in one interface and the methods in the other. This will enable us to use the constants in classes where the methods are
not required. Example:
interface ItemConstants
{
int code=1001;
String name=”xyz”;
}
interface Item extends ItemConstants
{
void display ();
}
The interface Item would inherit both the constants code and name into it. Note that the variables name and code are declared like simple variables. It is
allowed because all the variables in an interface are treated as constants through the keywords final and static are not present.
We can also combine several interfaces together into a single interface. Following declarations are valid:
interface ItemConstants
{
int code=1001;
String name=”xyz”;
}
interface ItemMethods
{
void display();
}
interface Item extends ItemConstants,ItemMethods
{………………..}
…………………………
While interfaces are allowed to extend to other interfaces, sub interfaces cannot define the methods declared in the super interfaces. After all, sub interfaces are
still interfaces, not classes. Instead, it is the responsibility of any class that implements the derived interface to define all the methods. Note that when an
interface extends two or more interfaces, they are separated by commas.
It is very important to note that an interface cannot extend classes. This would violate the rule that an interface can have only abstract methods and
constants.
Implementing Interfaces:
Interfaces are used as “super classes” whose properties are inherited by classes. It is therefore necessary to create a class that inherits the given interface. This is
done as follows.
class class_name implements interface_name
{
Body of class name
Here the class class_name implements the interface interface_name. A more general form of implementation may look like this.
class class_name extends superclass
implements interface1, interface2…
{
Body of classname
}
This shows that a class can extend another class while implementing interfaces.
When a class implements more than one interface, they are separated by a comma. The implementation of interfaces can take various forms can be illustrated in
the following example.
interface Area
{
final static float pi=3.14F;
float compute(float x,float y);
}
class Rect1 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);
}
}
public class InterfaceTest {
public static void main(String[] args)
{
Rect1 rect=new Rect1();
Circle cir=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.0
Area of Circle =314.0
In the above program, first we create an interface Area and implement the same in two different classes, Rect1 and Circle. We create an instance of each class
using the new operator. Then we declare an object of type Area, the interface class. Now, we assign the reference to the rectangle object rect to area. When we
call the compute method of area, the compute method of Rect1 class is invoked. We repeat the same thing with the Circle object.
Accessing Interface variables:
Interfaces can be used to declare a set of constants that can be used in different classes. This is similar to creating header files in C++ to contain a large number
of constants. Since such interfaces do not contain methods, there is no need to worry about implementing any methods. The constant values will be available to
any class that implements the interface. The values can be used in any method, as part of any variable declaration, or anywhere where we can use a final value.
Example:
interface A
{
int m=10;
int n=50;
}
class B implements A
{
int x=m;
void methodB(int size)
{
………….
…………
if(size<n)
…………
}
}
The following program illustrates the implementation of multiple inheritance using interfaces.
class Student
{
int rollNumber;
void getNumber(int n)
{
rollNumber=n;
}
void putNumber()
{
[Link]("Roll No: " +rollNumber);
}
}
class Test1 extends Student
{
float part1,part2;
void getMarks(float m1,float m2)
{
part1=m1;
part2=m2;
}
void putMarks()
{
[Link]("Marks Obtained");
[Link]("part1=" +part1);
[Link]("part2=" +part2);
}
}
interface Sports
{
float sportWt=6.0F;
void putWt();
}
class Results extends Test1 implements Sports
{
float total;
public void putWt()
{
[Link]("Sports Wt=" +sportWt);
}
void display()
{
total=part1+part2+sportWt;
putNumber();
putMarks();
putWt();
[Link]("Total score=" +total);
}
}
public class Hybrid {
public static void main(String[] args)
{
Results student1=new Results ();
[Link](1234);
[Link](27.5F,33.0F);
[Link]();
}
}
Output:
Roll No: 1234
Marks Obtained
part1=27.5
part2=33.0
Sports Wt=6.0
Total score=66.5
Inner classes in Java:
A Java inner class is a class that is defined inside another class. The concept of inner class works with nested Java classes where outer and inner classes are used.
The main class in which inner classes are defined is known as the outer class and all other classes which are inside the outer class are known as Java inner
classes.
The following is the syntax of Java inner classes.
class OuterDemo
{
class InnerDemo
{
……
…….
}}
There are certain advantages associated with inner classes are as follows:
Making code readable and understandable.
Private methods of the outer class can be accessed, so bringing a new dimension and making it closer to the real world.
Optimizing the code module.
Types of Inner Classes
There are basically four types of inner classes in java.
Nested Inner Class
Static Nested Classes
Anonymous Inner Classes
Nested Inner Class
It can access any private instance variable of the outer class. Like any other instance variable, we can have access modifier private, protected, public, and default
modifier. Like class, an interface can also be nested and can have access specifier.
Example Program:
class Outer {
class Inner {
public void show ()
{
[Link] ("In a nested class method");
}
}
}
class InnerOuter {
public static void main (String [] args)
{
[Link] in = new Outer ().new Inner ();
[Link] ();
}
}
Output:
In a nested class method
Static Nested Classes or Static inner class:
Static nested classes are not technically inner classes. They are like a static member of outer class.
Example Program:
import [Link].*;
class Outer {
private static void outerMethod()
{
[Link] ("inside outerMethod");
}
static class Inner {
public static void display()
{
[Link] ("inside inner class Method");
outerMethod();
}
}
}
class InnerStatic
{
public static void main (String args [])
{[Link]. display();
}}
Output:
inside inner class Method
inside outerMethod
Anonymous Inner Classes
Anonymous inner classes are declared without any name at all. They are created in two ways.
As a subclass of the specified type
As an implementer of the specified interface
Example Program:
import [Link].*;
class Demo {
void show ()
{
[Link]("i am in show method of super class");
}
}
class Anony {
static Demo d = new Demo() {
void show ()
{
[Link] ();
[Link] ("i am in Flavor1Demo class");
}
};
public static void main (String [] args)
{
[Link]();
}
}
Packages in Java:
In programming, it is often helpful to group related pieces of a program together. In java, this is accomplished by using a package. A package serves two
purposes. First it provides a mechanism