0% found this document useful (0 votes)
6 views30 pages

Inheritance and Interfaces in Java

The document covers the concepts of inheritance and interfaces in Java, explaining inheritance as the process where one class acquires properties from another, and detailing member access, method overriding, and the use of the 'super' keyword. It also introduces abstract classes and interfaces, highlighting their syntax, advantages, and implementation. Key examples illustrate these concepts, including the use of constructors, dynamic method dispatch, and the final keyword.

Uploaded by

leelarani
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)
6 views30 pages

Inheritance and Interfaces in Java

The document covers the concepts of inheritance and interfaces in Java, explaining inheritance as the process where one class acquires properties from another, and detailing member access, method overriding, and the use of the 'super' keyword. It also introduces abstract classes and interfaces, highlighting their syntax, advantages, and implementation. Key examples illustrate these concepts, including the use of constructors, dynamic method dispatch, and the final keyword.

Uploaded by

leelarani
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 3 Inheritance and Interfaces

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

• Used in method overriding (so runtime polymorphism can be achieved).

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

[Link]("i+j+k: " + (i+j+k));


}
}
class SimpleInheritance
{
public static void main(String args [])
{
B subOb = new B();

/* The subclass has access to all public members of its superclass. */


subOb.i = 7;
subOb.j = 8;
subOb.k = 9;

[Link]("Contents of subOb: ");


[Link]();
[Link]();
[Link]();
[Link]("Sum of i, j and k in subOb:");
[Link]();
}
}

Member Access and Inheritance


Although a subclass includes all of the members of its super class, it cannot access those
members of the super class that have been declared asprivate. For example, consider the
following simple class hierarchy:

/* 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

void setij(int x, int y)


{
i = x;
j = y;
}
}
class B extends A
{
int total;
void sum()
{
total = i + j; //A's j is not accessible here
}
}
class SimpleInheritance2
{
public static void main(String args[])
{
B subOb = new B();
[Link](10, 12);
[Link]();
[Link]("Total is " + [Link]);
}
}

A super class variable can reference a subclass object:


A reference variable of a super class can be assigned a reference to any subclass derived
from that super class.
Ex:
class A
{
void callMe()
{
[Link]("Hello");
}
}
3
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:

–super is used to refer immediate parent class instance variable.


super.parent_instance_variable_name;
–super is used to invoke immediate parent class method
super.parent_class_method_name();
–super is used to invoke immediate parent class constructor.
super(arglist); // parameterized constructor
super(); //default

4
Unit 2 Inheritance and Interfaces

Usage 1. - Using super to refer super class property


class Vehicle
{
int speed=50;
}
class Bike extends Vehicle
{
int speed=100;
void display()
{
[Link]("Vehicle Speed:"+[Link]);//will print speed of vehicle
[Link]("Bike Speed:"+speed);//will print speed of bike
}
}
class SuperVarible
{
public static void main(String args[])
{
Bike b=new Bike();
[Link]();
}
}

Output:

Usage 2. - super is used to invoke immediate parent class method

class Student
{
void message()
{
[Link]("Good Morning Sir");
}
}

class Faculty extends Student


{
5
Unit 2 Inheritance and Interfaces

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:

Usage 3. - super is used to invoke immediate parent class constructor


class Vehicle
{
Vehicle( )
{
[Link]("Vehicle is created");
}
}

class Bike extends Vehicle


{
Bike()
{
super( );//will invoke parent class constructor
[Link]("Bike is created");
}

}
class SuperClassConst
{
6
Unit 2 Inheritance and Interfaces

public static void main(String args[])


{
Bike b=new Bike();
}
}

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:

Dynamic Method Dispatch:


Dynamic method dispatch is the mechanism by which a call to an overridden method is
resolved at run time, rather than compile time. Dynamic method dispatch is important because
this is how Java implements run-time polymorphism.
Example://A Superclass Variable Can Reference to a Subclass Object
class A
{
void callMe()
{
[Link]("Inside A");
}
}
class B extends A
{
void callMe()
{
[Link]("Inside B");
}
}

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:

Applying Method Overriding:

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

ECEStudent ece=new ECEStudent();

Student sref;

sref=it;
[Link]();
[Link]();

sref=cse;
[Link]();
[Link]();

sref=ece;
[Link]();
[Link]();
}
}

Abstract Class

• An abstract class is a class that contains one or more abstract methods.


• An abstract method is a method without method body.
Syntax:
abstract return_type method_name(parameter_list);
• An abstract class can contain instance variables, constructors, concrete methods in
addition to abstract methods.
• All the abstract methods of abstract class should be implemented in its sub classes.
• If any abstract method is not implemented in its subclasses, then that sub class must be
declared as abstract.
• We cannot create an object to abstract class, but we can create reference of abstract
class.
• Also, you cannot declare abstract constructors or abstract static methods.
Example 1: Java program to illustrate abstract class.
abstract class MyClass
{
abstract void calculate(double x);
}
class Sub1 extends MyClass
{
void calculate(double x)
12
Unit 2 Inheritance and Interfaces

{
[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);
}
}

Example 2: Java program to illustrate abstract class.

// A Simple demonstration of abstract.


abstract class A
{
abstract void callme();
// concrete methods are still allowed in abstract classes
void callmetoo() {
[Link]("This is a concrete method.");
}
}
class B extends A
{
void callme()
13
Unit 2 Inheritance and Interfaces

{
[Link]("B's implementation of callme.");
}
}

class AbstractDemo
{
public static void main(String args[])
{
B b = new B();
[Link]();
[Link]();
}
}

Uses of Final:

Final can be used in three ways:


• To prevent modifications to the instance variable
• To Prevent method overriding
• To prevent inheritance
Use 2: To prevent method overriding
class Vehicle
{
final void run()
{
[Link]("running");
}
}
class Bike extends Vehicle
{
void run()
{
[Link]("running safely with 100kmph");
}
}

class FinalMethod
{
public static void main(String args[])
{
Bike b= new Bike();
[Link]();
14
Unit 2 Inheritance and Interfaces

}
}
Error Information:

Use 3: To prevent inheritance


final class Vehicle
{
void run()
{
[Link]("running");
}
}
class Bike extends Vehicle
{
void run()
{
[Link]("running safely with 100kmph");
}
}

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.

A Java interface is a c llection of constants and abstract methods

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

Example 2: Write a java program to implement interface.


interface Teacher
{
void display1();
}
interface Student
{
void display2();
}
class College implements Teacher, Student
{
public void display1()
{
[Link]("Hi I am Teacher");
}
public void display2()
{
[Link]("Hi I am Student");
}
}
class CollegeData
{
public static void main(String arh[])
{
College c=new College();
c.display1();
c.display2();
}
}

Accessing implementations through interface references:


We can declare variables as object references that use an interface rather than a class
type. Any instance of any class that implements the declared interface can be referred to by such
a variable. When you call a method through one of these references, the correct version will be
called based on the actual instance of the interface being referred to. This is one of the key
features of interfaces. The method to be executed is looked up dynamically at run time,
allowing classes to be created later than the code which calls methods on them.

18
Unit 2 Inheritance and Interfaces

Ex:
interface Test {

void call();
}

class InterfaceTest implements Test {

public void call()


{
[Link]("call method called");
}
}

public class IntefaceReferences {

public static void main(String[] args)


{
Test f ;
InterfaceTest it= new InterfaceTest();
f=it;
[Link]();
}
}

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.

Example:Java program to demonstrate variables in interface.


interface left
{
int i=10;
}
interface right
19
Unit 2 Inheritance and Interfaces

{
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*/
}
}

Interfaces can be extended:


One interface can inherit another by use of the keywordextends. The syntax is the same
as for inheriting classes. When a class implements an interface that inherits another interface,
it must provide implementations for all methods defined within the interface inheritance chain.

Example:Java program to demonstrate interfaces can be extended with extend keyword.


interface Teacher
{
void display1();
}
interface Student
{
void display2();
}
interface T_S extends Teacher, Student
{
void display3();
}
class College implements T_S
{
public void display1()
{
[Link]("Hi I am Teacher");
}
public void display2()
{
[Link]("Hi I am Student");
}
public void display3()
{
[Link]("Hi I am Teacher_Student");

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

Difference between Interface and Abstract class:

Abstract Class Interface

Contains some abstract methods and some


Only abstract methods
concrete methods

Contains instance variables Only static and final variables

Doesn‟t support multiple inheritance Supports

public class Person implements


public class Apple extends Food { … }
Student,Athlete,Chef { … }

Packages:

• A Package can be defined as a grouping of related types(classes, interfaces)


• A package represents a directory that contains related group of classes and interfaces.
• Packages are used in Java in order to prevent naming conflicts.
• There are two types of packages in Java.
1. Pre-defined Packages(built-in)
2. User defined packages
Pre-defined Packages:
Package
Description
Name
Contains language support classes (for e.g classes which defines
[Link] primitive data types, math operations, etc.). This package is
automatically imported.
[Link] Contains classes for supporting input / output operations.
Contains utility classes which implement data structures like Linked
[Link] List, Hash Table, Dictionary, etc and support for Date / Time operations.
This package is also called asCollections.

[Link] Contains classes for creating Applets.

Contains classes for implementing the components of graphical user


[Link]
interface ( like buttons, menus, etc. ).

22
Unit 2 Inheritance and Interfaces

[Link] Contains classes for supporting networking operations.


This package helps to develop GUI like [Link]. The „x‟ in javax
represents that it is an extended package which means it is a package
[Link]
developed from another package by adding new features to it. In fact,
[Link] is an extended package of [Link].
This package helps to connect to databases like Oracle/Sybase/Microsoft
[Link]
Access to perform different operations.

Defining a Package(User defined):


To create a package is quite easy: simply include apackagecommand as the first
statement in a Java source file. Any classes declared within that file will belong to the specified
package. Thepackagestatement defines a name space in which classes are stored. If you omit
thepackagestatement, the class names are put into the default package, which has no name.
This is the general form of thepackagestatement:
packagepkg;
Here,pkgis the name of the package.
For example, the following statement creates a package calledMyPackage:
package MyPackage;
Java uses file system directories to store packages. For example, [Link] for any
classes you declare to be part ofMyPackagemust be stored in a directory calledMyPackage.
Remember that case is significant, and the directory name must match the package name
exactly. More than one file can include the samepackagestatement.
Thepackagestatement simply specifies to which package the classes defined in a file
belong. It does not exclude other classes in other files from being part of that same package.
Most real-world packages are spread across many files. You can create a hierarchy of packages.
To do so, simply separate each package name from the one above it by use of a period. The
general form of a multileveled package statement is shown here:
packagepkg1[.pkg2[.pkg3]];
A package hierarchy must be reflected in the file system of your Java development system. For
example, a package declared as
package [Link];

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));
}
}

Step 2:Save the above file with [Link]


Step 3:Compilation
To compile the java files use the following commands
javac -d directory_path name_of_the_java file
Javac –d . name_of_the_java file
Note: -d is a switching options creates a new directory with package name. Directory
path represents in which location you want to create package and . (dot) represents
current working directory.
24
Unit 2 Inheritance and Interfaces

Step 4:Access package from another package


There are three ways to use package in another package:
[Link] fully qualified name.
class UseofPack
{
public static void main(String arg[])
{
[Link] a=new [Link](10,15);
[Link]();
[Link] s=new [Link](20,15);
[Link]();
}
}
2. import [Link];

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

Note:Don‟t place [Link], [Link] files parallel to the pack directory. If


you place JVM searches for the class files in the current working directory not in the
pack directory.

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;

public class Protection


{
int n = 1;
private int n_priv = 2;
protected int n_prot = 3;
public int n_publ = 4;

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);
}
}

This is file [Link]:


package pkg1;

class Derived extends Protection


{
Derived()
{
[Link]("Same package - derived (from base) constructor");
[Link]("n = " + n);

/* class only
* [Link]("n_priv = "4 + n_priv); */

[Link]("n_prot = " + n_prot);


[Link]("n_publ = " +n_publ);
}
}

This is file [Link]

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); */

[Link]("n_prot = " + pro.n_prot);


27
Unit 2 Inheritance and Interfaces

[Link]("n_publ = " + pro.n_publ);


}
}

Name of the package:pkg2

This is file [Link]:

package pkg2;

class Protection2 extends [Link]


{
Protection2()
{
[Link]("Other package-Derived (from Package 1-Base)
Constructor");

/* class or package only


* [Link]("n = " + n); */

/* class only
* [Link]("n_priv = " + n_priv); */

[Link]("n_prot = " + n_prot);


[Link]("n_publ = " + n_publ);
}
}

This is [Link]
package pkg2;

class OtherPackage
{
OtherPackage()
{
[Link] pro = new [Link]();

[Link]("other package - Non sub class constructor");

/* class or package only


* [Link]("n = " + pro.n); */

/* class only
* [Link]("n_priv = " + pro.n_priv); */

/* class, subclass or package only


28
Unit 2 Inheritance and Interfaces

* [Link]("n_prot = " + pro.n_prot); */

[Link]("n_publ = " + pro.n_publ);


}
}

If you want to try these t two packages, here are two test files you can use. The one for
packagepkg1is shown here:

/* demo package pkg1 */

package pkg1;

/* instantiate the various classes in pkg1 */


public class Demo
{
public static void main(String args[])
{
Derived obj2 = new Derived();
SamePackage obj3 = new SamePackage();
}
}

The test file for package pkg2 is

package pkg2;

/* instantiate the various classes in pkg2 */


public class Demo2
{
public static void main(String args[])
{
Protection2 obj1 = new Protection2();
OtherPackage obj2 = new OtherPackage();
}
}

29
Unit 2 Inheritance and Interfaces

30

You might also like