Inheritance and Interfaces in Java
Inheritance and Interfaces in Java
Inheritance:
• Inheritance can be defined as the process where one class acquires the properties of
another class
• The class which inherits the properties of other is known as subclass (derived class,
child class) and the class whose properties are inherited is known as superclass (base
class, parent class).
• Inheritance represents theIS-A relationship, also known asparent-childrelationship.
• Advantages of inheritance:
• Code reusability
Syntax:
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.
Example:
// A simple example of inheritance.
// Create a superclass.
class A
{
int i, j;
void showij()
{
[Link]("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A
{
int k;
void showk()
{
[Link]("k: "+ k);
}
void sum()
{
1
Unit 3 Inheritance and Interfaces
/* In a class hierarchy, private members remain private to their class. This program contains an
error and will not compile. */
class A
{
int i; // public by default
private int j; //Private to A
2
Unit 2 Inheritance and Interfaces
class B extends A
{
void callMe()
{
[Link]("Hi ");
}
}
class Reference
{
public static void main(String args[])
{
A ref;
B b = new B();
ref = b;
[Link]();
}
}
Output:Hi
Using super
Whenever the derived class inherits the base class features, there is a possibility that
base class features are similar to derived class features and JVM gets an ambiguity. To
overcome this, super is used to refer super class properties.
Thesuperkeyword in java is a reference variable that is used to refer parent class. The
keyword “super” came into the picture with the concept of Inheritance. It is majorly used in the
following contexts:
4
Unit 2 Inheritance and Interfaces
Output:
class Student
{
void message()
{
[Link]("Good Morning Sir");
}
}
void message()
{
[Link]("Good Morning Students");
}
void display()
{
message();//will invoke or call current class message() method
[Link]();//will invoke or call parent class message() method
}
}
class SuperClassMethod
{
public static void main(String args[])
{
Faculty f=new Faculty();
[Link]();
}
}
Output:
}
class SuperClassConst
{
6
Unit 2 Inheritance and Interfaces
Output:
Calling Constructors:
Constructors are called in order of derivation, from super class to sub class. Further,
sincesuper( )must be the first statement executed in a subclass‟ constructor , this order is the
same whether or notsuper( )is used. Ifsuper( )is not used, then the default constructor of
each super class will be executed. The following program illustrates when constructors are
executed:
// Create a super class.
class A {
A() {
[Link]("Inside A's constructor.");
}
}
// Create a subclass by extending class A.
class B extends A
{
B() {
[Link]("Inside B's constructor.");
}
}
// Create another subclass by extending B.
class C extends B {
C() {
[Link]("Inside C's constructor.");
}
}
class CallingConstructor
{
public static void main(String args[])
{
7
Unit 2 Inheritance and Interfaces
C c = new C();
}
}
Output:
Method Overriding:
In a class hierarchy, when a method in a subclass has the same name and type signature
as a method in its superclass, then the method in the subclass is said tooverridethe method in
the superclass.
When an overridden method is called from within a subclass, it will always refer to the
version of that method defined by the subclass. The version of the method defined by the
superclass will be hidden.
Example:
// Method overriding.
class A
{
int i, j;
A(int a, int b)
{
i = a;
j = b;
}
// display i and j
void show()
{
[Link]("i and j: " + i + " " + j);
}
}
class B extends A
{
int k;
B(int a, int b, int c)
{
super(a, b);
8
Unit 2 Inheritance and Interfaces
k = c;
}
// display k – this overrides show() in A
void show()
{
[Link]("k: " + k);
}
}
class Override
{
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
[Link](); // this calls show() in B
}
}
Output:
class C extends B
{
9
Unit 2 Inheritance and Interfaces
void callMe()
{
[Link]("Inside C");
}
}
class DynamicMethodDispatch
{
public static void main(String args[])
{
A a=new A();
B b = new B();
C c = new C();
A ref;
ref = a;
[Link]();
ref = b;
[Link]();
ref=c;
[Link]();
}
}
Output:
import [Link].*;
class Student
{
int n;
String name;
void read()
{
Scanner s=new Scanner([Link]);
[Link]("Enter no and Name");
n=[Link]();
name=[Link]();
}
10
Unit 2 Inheritance and Interfaces
void show()
{
[Link]("No:"+n);
[Link]("Name:"+name);
}
}
class ITStudent extends Student
{
void read()
{
[Link]();
}
void show()
{
[Link]();
}
}
class CSEStudent extends Student
{
void read()
{
[Link]();
}
void show()
{
[Link]();
}
}
class ECEStudent extends Student
{
void read()
{
[Link]();
}
void show()
{
[Link]();
}
}
class MainMethod
{
public static void main(String ar[])
{
ITStudent it=new ITStudent();
CSEStudent cse=new CSEStudent();
11
Unit 2 Inheritance and Interfaces
Student sref;
sref=it;
[Link]();
[Link]();
sref=cse;
[Link]();
[Link]();
sref=ece;
[Link]();
[Link]();
}
}
Abstract Class
{
[Link]("Square :"+(x*x));
}
}
class Sub2 extends MyClass
{
void calculate(double x)
{
[Link]("Square Root :"+[Link](x));
}
}
class Sub3 extends MyClass
{
void calculate(double x)
{
[Link]("Cube :"+(x*x*x));
}
}
class AC
{
public static void main(String arg[])
{
Sub1 obj1=new Sub1();
Sub2 obj2=new Sub2();
Sub3 obj3=new Sub3();
[Link](20);
[Link](20);
[Link](20);
}
}
{
[Link]("B's implementation of callme.");
}
}
class AbstractDemo
{
public static void main(String args[])
{
B b = new B();
[Link]();
[Link]();
}
}
Uses of Final:
class FinalMethod
{
public static void main(String args[])
{
Bike b= new Bike();
[Link]();
14
Unit 2 Inheritance and Interfaces
}
}
Error Information:
class FinalClass
{
public static void main(String args[])
{
Bike b= new Bike();
[Link]();
}
}
15
Unit 2 Inheritance and Interfaces
Interfaces:
A named collection of ethod declarations.
S ince all methods in a interface are abstract, the abstract modifier is usually left off
Using interface, you c n specify what a class must do, but not how t does.
Interface fields are public, static and final by default, and methods re public and abstract.
Advantages of interfaces:
•I t is used to achieve abstraction.
• By interface, we ca support the functionality of multiple inherit nces.
Syntax:
access_specif er interface interfae_name
{
return type method-name1(parameter-list);
return type method-name2(parameter-list);
type fi al-varname1 = value;
type fi al-varname2 = value;
//...
return type method-nameN(parameter-list);
type fi al-varnameN = value;
}
16
Unit 2 Inheritance and Interfaces
Implementing Interfaces:
• Once an interface has been defined, one or more classes can implement that interface.
• To implement an interface, include the implements clause in a class definition, and then
create the methods defined by the interface.
• The general form of a class that includes theimplements clause looks like this:
classclassname [extends superclass] [implements interface1 [,interface2...]] {
// class-body
}
• If a class implements more than one interface, the interfaces are separated with a
comma.
• The methods that implement an interface must be public. Also, the type signature of
implementing method must match exactly the type signature specified in interface
definition.
Example 1: Write a java program to implement interface.
interface Moveable
{
int AVG_SPEED=30;
void Move();
}
class Move implements Moveable
{
void Move(){
System .out. println ("Average speed is: "+AVG_SPEED );
}
}
class Vehicle
{
public static void main (String[] arg)
{
Move m = new Move();
[Link]();
}
}
17
Unit 2 Inheritance and Interfaces
18
Unit 2 Inheritance and Interfaces
Ex:
interface Test {
void call();
}
Variables in Interfaces:
We can use interfaces to import shared constants into multiple classes by simply
declaring an interface that contains variables that are initialized to the desired values. When we
include that interface in a class (that is, when you “implement” the interface), all of those
variable names will be in scope as constants. (This is similar to using a header file in C/C++ to
create a large number of#definedconstants orconstdeclarations). If an interface contains no
methods, then any class that includes such an interface doesn‟t actually implement anything. It
is as if that class were importing the constant fields into the class name space asfinalvariables.
{
int i=100;
}
class Test implements left,right
{
public static void main(String args[])
{
[Link](left.i);//10 will be printed
[Link](right.i);//100 will be printed*/
}
}
20
Unit 2 Inheritance and Interfaces
}
}
class Class_Interface
{
public static void main(String arh[])
{
College c=new College();
c.display1();
c.display2();
c.display3();
}
Example 2:Java program to implement interface and inheriting the properties from a class.
interface Teacher
{
void display1();
}
class Student
{
void display2()
{
[Link]("Hi I am Student");
}
}
class College extends Student implements Teacher
{
public void display1()
{
[Link]("Hi I am Teacher");
}
}
class Interface_Class
{
public static void main(String arh[])
{
College c=new College();
c.display1();
c.display2();
}
}
21
Unit 2 Inheritance and Interfaces
Packages:
22
Unit 2 Inheritance and Interfaces
23
Unit 2 Inheritance and Interfaces
Example:Package demonstration
package pack;
public class Addition
{
int x,y;
public Addition(int a, int b)
{
x=a;
y=b;
}
public void sum()
{
[Link]("Sum :"+(x+y));
}
}
Step 1:Save the above file with [Link]
package pack;
public class Subtraction
{
int x,y;
public Subtraction(int a, int b)
{
x=a;
y=b;
}
public void diff()
{
[Link]("Difference :"+(x-y));
}
}
import [Link];
import [Link];
class UseofPack
{
public static void main(String arg[])
{
Addition a=new Addition(10,15);
[Link]();
Subtraction s=new Subtraction(20,15);
[Link]();
}
}
3. import package.*;
import pack.*;
class UseofPack
{
public static void main(String arg[])
{
Addition a=new Addition(10,15);
[Link]();
Subtraction s=new Subtraction(20,15);
[Link]();
}
}
25
Unit 2 Inheritance and Interfaces
Access Protection
• Access protection defines actually how much an element (class, method, variable) is
exposed to other classes and packages.
• There are four types of access specifiers available in java:
1. Visible to the class only (private).
2. Visible to the package (default). No modifiers are needed.
3. Visible to the package and all subclasses (protected)
4. Visible to the world (public)
Example:
The following example shows all combinations of the access control modifiers. This
example has two packages and five classes. The source for the first package defines three
classes:Protection,Derived, andSamePackage.
Name of the package:pkg1
This file is [Link]
package pkg1;
26
Unit 2 Inheritance and Interfaces
public Protection()
{
[Link]("base constructor");
[Link]("n = " + n);
[Link]("n_priv = " + n_priv);
[Link]("n_prot = " + n_prot);
[Link]("n_publ = " + n_publ);
}
}
/* class only
* [Link]("n_priv = "4 + n_priv); */
package pkg1;
class SamePackage
{
SamePackage()
{
Protection pro = new Protection();
[Link]("same package - other constructor");
[Link]("n = " + pro.n);
/* class only
* [Link]("n_priv = " + pro.n_priv); */
package pkg2;
/* class only
* [Link]("n_priv = " + n_priv); */
This is [Link]
package pkg2;
class OtherPackage
{
OtherPackage()
{
[Link] pro = new [Link]();
/* class only
* [Link]("n_priv = " + pro.n_priv); */
If you want to try these t two packages, here are two test files you can use. The one for
packagepkg1is shown here:
package pkg1;
package pkg2;
29
Unit 2 Inheritance and Interfaces
30