Unit 2
Unit 2
1. Inheritance
• Use of inheritance
o Inheritance is one of the cornerstones of object-oriented programming
because it allows the creation of hierarchical classifications.
o Using inheritance, you can create a general class that defines traits
common to 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.
o In the terminology of Java, a class that is inherited is called a superclass.
o The class that does the inheriting is called a subclass.
o To inherit a class, you simply incorporate the definition of one class into
another by using the extends keyword.
o The general form of a class declaration that inherits a superclass is shown
here:
class subclass-name extends superclass-name {
// body of class
}
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
/* The subclass has access to all public members of
its superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}
o Member Access and Inheritance
▪ Although a subclass includes all of the members of its superclass,
it cannot access those members of the superclass that have been
declared as private.
// Create a superclass.
class A {
int i; // public by default
private int j; // private to A
void setij(int x, int y)
{
i = x;
j = y;
}
}
// A's j is not accessible here.
class B extends A {
int total;
void sum() {
total = i + j; // ERROR, j is not accessible here
}
}
2
Subject: Programming with Java (102044502)
Unit 2: Inheritance, Interface
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
class Access {
public static void main(String args[])
{
B subOb = new B();
subOb.setij(10, 12);
subOb.sum();
System.out.println("Total is " + subOb.total);
}
}
o 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.
// 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);
k = c;
}
// display k – this overrides show() in A
void show() {
System.out.println("k: " + k);
}
}
3
Subject: Programming with Java (102044502)
Unit 2: Inheritance, Interface
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
class Override
{
public static void main(String args[])
{
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}
class DemoRef
{
public static void main(String args[])
4
Subject: Programming with Java (102044502)
Unit 2: Inheritance, Interface
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
{
Base ref;
Dirived obj = new Dirived();
ref = obj;
ref.Msg1();
}
}
o Using super
▪ Whenever a subclass needs to refer to its immediate superclass, it
can do so by use of the keyword super.
▪ Usage of Java super Keyword
• super can be used to refer immediate parent class instance
variable.
o 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(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of
Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
5
Subject: Programming with Java (102044502)
Unit 2: Inheritance, Interface
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}
6
Subject: Programming with Java (102044502)
Unit 2: Inheritance, Interface
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}
• Object Class
o The Object class is the parent class of all the classes in java by default. In
other words, it is the topmost class of java.
o If a class does not extend any other class then it is a direct child class of
Object and if extends another class then it is indirectly derived.
o The Object class is beneficial if you want to refer any object whose type
you don't know. Notice that parent class reference variable can refer the
child class object, know as upcasting.
o Using Object Class Methods
▪ The Object class provides multiple methods which are as follows:
• tostring() method
• hashCode() method
• equals(Object obj) method
• finalize() method
• getClass() method
• clone() method
• wait(), notify() notifyAll() methods
7
Subject: Programming with Java (102044502)
Unit 2: Inheritance, Interface
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
• types of inheritance
Java supports the following four types of inheritance:
o Single Inheritance
▪ In single inheritance, a sub-class is derived from only one super
class. It inherits the properties and behavior of a single-parent
class. Sometimes it is also known as simple inheritance.
o Multi-level Inheritance
▪ In multi-level inheritance, a class is derived from a class which is
also derived from another class is called multi-level inheritance. In
simple words, we can say that a class that has more than one
parent class is called multi-level inheritance. Note that the classes
8
Subject: Programming with Java (102044502)
Unit 2: Inheritance, Interface
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
float marks;
void getMarks(float m)
{
marks=m;
}
void putMarks()
{
System.out.println("marks= "+marks);
}
}
//derived class
class Sports extends Marks
{
float score;
void getScore(float scr)
{
score=scr;
}
void putScore()
{
System.out.println("score= "+score);
}
}
public class MultilevelInheritanceExample
{
public static void main(String args[])
{
Sports ob=new Sports();
ob.getNo(0987);
ob.putNo();
ob.getMarks(78);
ob.putMarks();
ob.getScore(68.7);
ob.putScore();
}
}
10
Subject: Programming with Java (102044502)
Unit 2: Inheritance, Interface
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
o Hierarchical Inheritance
▪ If a number of classes are derived from a single base class, it is
called hierarchical inheritance.
}
class Arts extends Student
{
public void methodArts()
{
System.out.println("The method of the class Arts invoked.");
}
}
public class HierarchicalInheritanceExample
{
public static void main(String args[])
{
Science sci = new Science();
Commerce comm = new Commerce();
Arts art = new Arts();
//all the sub classes can access the method of super class
sci.methodStudent();
comm.methodStudent();
art.methodStudent();
}
}
o Hybrid Inheritance
▪ Hybrid means consist of more than one. Hybrid inheritance is the
combination of two or more types of inheritance.
12
Subject: Programming with Java (102044502)
Unit 2: Inheritance, Interface
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
obj.show();
}
}
14
Subject: Programming with Java (102044502)
Unit 2: Inheritance, Interface
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
Example:
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
15
Subject: Programming with Java (102044502)
Unit 2: Inheritance, Interface
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
Example:
abstract class Bank{
abstract int getRateOfInterest();
}
class SBI extends Bank{
int getRateOfInterest(){return 7;}
}
class PNB extends Bank{
int getRateOfInterest(){return 8;}
}
class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+"
%");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+"
%");
}}
16
Subject: Programming with Java (102044502)
Unit 2: Inheritance, Interface
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
class B extends A {
// override callme()
void callme() {
System.out.println("Inside B's callme method");
}
}
class C extends A {
// override callme()
void callme() {
System.out.println("Inside C's callme method");
}
}
class Dispatch {
public static void main(String args[]) {
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A
r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}
}
2. Interface
• Defining an Interface
o Interfaces are syntactically similar to classes, but they lack instance
variables, and their methods are declared without any body.
o Using the keyword interface, you can fully abstract a class’ interface from
its implementation.
o Using interface, you can specify what a class must do, but not how it does
it.
o An interface is defined much like a class. This is the general form of an
interface:
17
Subject: Programming with Java (102044502)
Unit 2: Inheritance, Interface
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
interface Callback {
void callback(int param);
}
• Implementing Interfaces
o Once an interface has been defined, one or more classes can implement
that interface.
o To implement an interface, include the implements clause in a class
definition, and then create the methods defined by the interface.
18
Subject: Programming with Java (102044502)
Unit 2: Inheritance, Interface
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
Example:
class Client implements Callback {
// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
void nonIfaceMeth() {
System.out.println("Classes that implement interfaces " +
"may also define other members, too.");
}
}
• Applying Interfaces
19
Subject: Programming with Java (102044502)
Unit 2: Inheritance, Interface
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
System.out.println("drawing circle");
}
}
class TestInterface1
{
public static void main(String args[])
{
Drawable d=new Circle();//In real scenario, object is provided by method
d.draw();
}
}
• Variables in Interfaces
You can use interfaces to import shared constants into multiple classes by simply
declaring an interface that contains variables which are initialized to the desired
values.
import java.util.Random;
interface SharedConstants {
int NO = 0;
int YES = 1;
int MAYBE = 2;
int LATER = 3;
int SOON = 4;
int NEVER = 5;
}
interface Printable
{
void print();
}
interface Showable
{
void show();
}
21
Subject: Programming with Java (102044502)
Unit 2: Inheritance, Interface
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
• Extended Interfaces
A class implements an interface, but one interface extends another interface.
interface Printable
{
void print();
}
interface Showable extends Printable
{
void show();
}
22