Unit 2
Unit 2
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 the IS-A relationship, also known as parent-child relationship.
• 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()
{
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A
{
int k;
void showk()
{
System.out.println("k: "+ k);
}
void sum()
{
1
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.
Unit 2 Inheritance, Packages 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
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.
Unit 2 Inheritance, Packages and Interfaces
class B extends A
{
void callMe()
{
System.out.print("Hi ");
}
}
class Reference
{
public static void main(String args[])
{
A ref;
B b = new B();
ref = b;
ref.callMe();
}
}
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.
The super keyword 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
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.
Unit 2 Inheritance, Packages and Interfaces
Output:
class Student
{
void message()
{
System.out.println("Good Morning Sir");
}
}
void message()
{
System.out.println("Good Morning Students");
}
void display()
{
message();//will invoke or call current class message() method
super.message();//will invoke or call parent class message() method
}
}
class SuperClassMethod
{
public static void main(String args[])
{
Faculty f=new Faculty();
f.display();
}
}
Output:
}
class SuperClassConst
{
6
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.
Unit 2 Inheritance, Packages and Interfaces
Output:
Calling Constructors:
Constructors are called in order of derivation, from super class to sub class. Further,
since super( ) must be the first statement executed in a subclass’ constructor, this order is the
same whether or not super( ) is used. If super( ) 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() {
System.out.println("Inside A's constructor.");
}
}
// Create a subclass by extending class A.
class B extends A
{
B() {
System.out.println("Inside B's constructor.");
}
}
// Create another subclass by extending B.
class C extends B {
C() {
System.out.println("Inside C's constructor.");
}
}
class CallingConstructor
{
public static void main(String args[])
{
7
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.
Unit 2 Inheritance, Packages 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 to override the 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()
{
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A
{
int k;
B(int a, int b, int c)
{
super(a, b);
8
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.
Unit 2 Inheritance, Packages and Interfaces
k = c;
}
// display k – this overrides show() in A
void show()
{
System.out.println("k: " + k);
}
}
class Override
{
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}
Output:
class C extends B
{
9
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.
Unit 2 Inheritance, Packages and Interfaces
void callMe()
{
System.out.println("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;
ref.callMe();
ref = b;
ref.callMe();
ref=c;
ref.callMe();
}
}
Output:
import java.util.*;
class Student
{
int n;
String name;
void read()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter no and Name");
n=s.nextInt();
name=s.nextLine();
}
10
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.
Unit 2 Inheritance, Packages and Interfaces
void show()
{
System.out.println("No:"+n);
System.out.println("Name:"+name);
}
}
class ITStudent extends Student
{
void read()
{
super.read();
}
void show()
{
super.show();
}
}
class CSEStudent extends Student
{
void read()
{
super.read();
}
void show()
{
super.show();
}
}
class ECEStudent extends Student
{
void read()
{
super.read();
}
void show()
{
super.show();
}
}
class MainMethod
{
public static void main(String ar[])
{
ITStudent it=new ITStudent();
CSEStudent cse=new CSEStudent();
11
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.
Unit 2 Inheritance, Packages and Interfaces
Student sref;
sref=it;
sref.read();
sref.show();
sref=cse;
sref.read();
sref.show();
sref=ece;
sref.read();
sref.show();
}
}
Abstract Class
{
System.out.println("Square :"+(x*x));
}
}
class Sub2 extends MyClass
{
void calculate(double x)
{
System.out.println("Square Root :"+Math.sqrt(x));
}
}
class Sub3 extends MyClass
{
void calculate(double x)
{
System.out.println("Cube :"+(x*x*x));
}
}
class AC
{
public static void main(String arg[])
{
Sub1 obj1=new Sub1();
Sub2 obj2=new Sub2();
Sub3 obj3=new Sub3();
obj1.calculate(20);
obj2.calculate(20);
obj3.calculate(20);
}
}
{
System.out.println("B's implementation of callme.");
}
}
class AbstractDemo
{
public static void main(String args[])
{
B b = new B();
b.callme();
b.callmetoo();
}
}
Uses of Final:
class FinalMethod
{
public static void main(String args[])
{
Bike b= new Bike();
b.run();
14
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.
Unit 2 Inheritance, Packages and Interfaces
}
}
Error Information:
class FinalClass
{
public static void main(String args[])
{
Bike b= new Bike();
b.run();
}
}
15
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.
Unit 2 Inheritance, Packages and Interfaces
Interfaces:
A named collection of method declarations.
A Java interface is a collection of constants and abstract methods
Since
ince all methods in an interface are abstract, the abstract modifier is usually left off
Using interface, you can specify what a class must do, but not how it does.
Interface fields are public, static and final by default, and methods are public and abstract.
Advantages of interfaces:
• Itt is used to achieve abstraction.
• By interface, we can support the functionality of multiple inheritances.
inheritances
Syntax:
access_specifier interface interfae_name
{
return--type method-name1(parameter-list);
return--type method-name2(parameter-list);
type final-varname1
final = value;
type final-varname2
final = value;
//...
return--type method-nameN(parameter-list);
type final-varnameN
final = value;
}
16
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.
Unit 2 Inheritance, Packages 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 the implements clause looks like this:
class classname [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();
m.Move();
}
}
17
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.
Unit 2 Inheritance, Packages and Interfaces
18
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.
Unit 2 Inheritance, Packages 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 #defined constants or const declarations). 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 as final variables.
{
int i=100;
}
class Test implements left,right
{
public static void main(String args[])
{
System.out.println(left.i);//10 will be printed
System.out.println(right.i);//100 will be printed*/
}
}
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()
{
System.out.println("Hi I am Teacher");
}
public void display2()
{
System.out.println("Hi I am Student");
}
public void display3()
{
System.out.println("Hi I am Teacher_Student");
20
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.
Unit 2 Inheritance, Packages 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()
{
System.out.println("Hi I am Student");
}
}
class College extends Student implements Teacher
{
public void display1()
{
System.out.println("Hi I am Teacher");
}
}
class Interface_Class
{
public static void main(String arh[])
{
College c=new College();
c.display1();
c.display2();
}
}
21
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.
Unit 2 Inheritance, Packages and Interfaces
Packages:
22
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.
Unit 2 Inheritance, Packages and Interfaces
23
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.
Unit 2 Inheritance, Packages and Interfaces
package pack;
public class Subtraction
{
int x,y;
public Subtraction(int a, int b)
{
x=a;
y=b;
}
public void diff()
{
System.out.println("Difference :"+(x-y));
}
}
import pack.Addition;
import pack.Subtraction;
class UseofPack
{
public static void main(String arg[])
{
Addition a=new Addition(10,15);
a.sum();
Subtraction s=new Subtraction(20,15);
s.difference();
}
}
3. import package.*;
import pack.*;
class UseofPack
{
public static void main(String arg[])
{
Addition a=new Addition(10,15);
a.sum();
Subtraction s=new Subtraction(20,15);
s.difference();
}
}
25
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.
Unit 2 Inheritance, Packages and Interfaces
Note: Don’t place Addition.java, Subtraction.java 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, and SamePackage.
Name of the package: pkg1
This file is Protection.java
package pkg1;
26
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.
Unit 2 Inheritance, Packages and Interfaces
public Protection()
{
System.out.println("base constructor");
System.out.println("n = " + n);
System.out.println("n_priv = " + n_priv);
System.out.println("n_prot = " + n_prot);
System.out.println("n_publ = " + n_publ);
}
}
/* class only
* System.out.println("n_priv = "4 + n_priv); */
package pkg1;
class SamePackage
{
SamePackage()
{
Protection pro = new Protection();
System.out.println("same package - other constructor");
System.out.println("n = " + pro.n);
/* class only
* System.out.println("n_priv = " + pro.n_priv); */
package pkg2;
/* class only
* System.out.println("n_priv = " + n_priv); */
class OtherPackage
{
OtherPackage()
{
pkg1.Protection pro = new pkg1.Protection();
/* class only
* System.out.println("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
package pkg1 is shown here:
package pkg1;
package pkg2;
29
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.
Unit 2 Inheritance, Packages and Interfaces
30
Dr. Suresh Yadlapati, M. Tech, Ph. D, Dept. of IT, PVPSIT.