You are on page 1of 36

Programming in Java

Inheritance
Inheritance
• Inheritance allows us to use one class by another class.

• A class that is derived from another class is called


a subclass (also a derived class, extended class, or child class).

• The class from which the subclass is derived is called
a superclass (also a base class or a parent class).

• Classes can be derived from classes that are derived from


classes that are derived from classes, and so on, and ultimately
derived from the topmost class called Object.
• Excepting Object, which has no superclass, every class has
one and only one direct superclass (single inheritance). In the
absence of any other explicit superclass, every class is
implicitly a subclass of Object.

• A subclass inherits all the members (fields, methods, and


nested classes) from its superclass. Constructors are not
members, so they are not inherited by subclasses, but the
constructor of the superclass can be invoked from the subclass.

• A class can inherits only one superclass at a time. But a class


can have several sub classes.
Simple Inheritance
• When a  subclass is derived simply from it's parent
class then this mechanism is known as simple
inheritance.

• In case of simple inheritance there is only a sub class


and it's parent class. It is also called single inheritance
or one level inheritance.   
• A subclass includes all of the members of its superclass, it
cannot access those members of the superclass that have been
declared as private.

• To inherit a class, you simply incorporate the definition of one


class into another by using the extends keyword.

• Syntax:
class sub_class_name extends super_class
{
//body of the sub class.
}
class A
{ int i, j;
void showij()
{
System.out.println("i and j: " + i + " " + j);
} }
class B extends A
{int k;
void showk()
{ System.out.println("k: " + k); }
void sum()
{ System.out.println("i+j+k: " + (i+j+k)); }
public static void main(String args[])
{B r=new B();
r.sum();
}
}
Multilevel Inheritance
• It is the enhancement of the concept of inheritance. When a
subclass is derived from a derived class then this mechanism
is known as the multilevel inheritance.

• The derived class is called the subclass or child class for it's
parent class and this parent class works as the child class for
it's just above (parent) class. 

• Multilevel inheritance can go up to any number of level.


class A 
{   int x;  int y;
  int get(int p, int q){  x=p; y=q; return(0);  }
  void Show() {System.out.println(x);}
}
class B extends A
{ void Showb() {System.out.println("B");}
}
class C extends B
{  void display() {System.out.println("C");}
public static void main(String args[])
{   C a = new C();
  a.get(5,6);
  a.Show();
}}
Multiple Inheritance
• The mechanism of inheriting the features of more than one
base class into a single class is known as multiple inheritance.

• Java does not support multiple inheritance but the multiple


inheritance can be achieved by using the interface.

• In Java Multiple Inheritance can be achieved through use of


Interfaces by implementing more than one interfaces in a
class.
Method Overloading
 Method overloading means having two or more methods with
the same name but different signatures in the same scope.

 It allows creating several methods with the same name which


differ from each other in the type of the input and the output of
the method.

 It is simply defined as the ability of one method to perform


different tasks.
Example
class Area11
{
void area(int a)
{
int area = a*a;
System.out.println("area of square is:" + area);
}
void area (int a, int b)
{
int area = a*b;
System.out.println("area of rectangle is:" + area);
}
}
class OverloadDemo
{
public static void main (String arr[])
{
Area11 ar= new Area11();
ar.area(10);
ar.area(10,5);
}
}
Method Overriding
• Method overriding means having a different implementation
of the same method in the inherited class.

• These two methods would have the same signature, but


different implementation.

• One of these would exist in the base class and another in the
derived class. These cannot exist in the same class.
• The version of a method that is executed will be determined
by the object that is used to invoke it.

• If an object of a parent class is used to invoke the method, then


the version in the parent class will be executed.

• If an object of the subclass is used to invoke the method, then


the version in the child class will be executed.
class Superclass
{ public void printMethod()
{ System.out.println("Printed in Superclass."); }
}
class Subclass extends Superclass
{ // overrides printMethod in Superclass
public void printMethod()
{ System.out.println("Printed in Subclass"); }
public static void main(String[] args)
{ Subclass s = new Subclass();
s.printMethod();
}
}
• output
• Printed in Subclass

• Within a class, a field that has the same name as a field in the
superclass hides the superclass's field, even if their types are
different. Within the subclass, the field in the superclass
cannot be referenced by its simple name.
class Override
{
public void display()
{
System.out.println("Hello...This is superclass display");
}
}

class Override1 extends Override


{
public void display()
{
System.out.println("Hi...This is overriden method in subclass");
}
}
class OverrideDemo
{
public static void main(String arr[])
{
Override o = new Override();
o.display();
Override1 o1 = new Override1();
o1.display();
}
}
Lets Do It
• Create a class Account having attributes name,
accountNumber and two methods to deposit and withdraw the
money.
• Create two subclasses CurrentAccount and SavingAccount of
Account with overridden methods deposit and withdraw.
• A current account has limit to withdraw while saving account
cannot have more than two transaction.
• Write a test program to use above classes and their methods.
Using Virtual Method Invocation
• class A {
   void callme() {
     System.out.println("Inside A's callme method");
   }
}
class B extends A {
   void callme() {
     System.out.println("Inside B's callme method");
   }
}
class C extends A {
   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
   }
}
Accessing Superclass Members
• If your method overrides one of its superclass's methods, you
can invoke the overridden method through the use of the
keyword super.
class Superclass
{ public void printMethod()
{
System.out.println("Printed in Superclass.");
}
}
class Subclass extends Superclass
{ // overrides printMethod in Superclass
public void printMethod()
{
super.printMethod();
System.out.println("Printed in Subclass");
}
public static void main(String[] args)
{ Subclass s = new Subclass();
s.printMethod();
}}
Using super
• A subclass can call a constructor defined by its superclass by
use of the following form of super:
super(arg-list);

• Here, arg-list specifies any arguments needed by the


constructor in the superclass.

• super( ) must always be the first statement executed inside a


subclass’ constructor.
class Superclass
{ Superclass()
{
System.out.println("Printed in Superclass.");
}
}
class Subclass extends Superclass
{ // overrides printMethod in Superclass
Subclass()
{
super();
System.out.println("Printed in Subclass");
}
public static void main(String[] args)
{ Subclass s = new Subclass();
}}
Private Members in a Superclass
•  A subclass does not inherit the private members of its parent
class. However, if the superclass has public or protected
methods for accessing its private fields, these can also be used
by the subclass.

 If subclass overrides public method of superclass, specify


call to public method of superclass:
super.MethodName(parameter list)
 If subclass does not override public method of superclass,
specify call to public method of superclass:
MethodName(parameter list)
Abstract Methods
• A method that has only the heading with no
body.
• Must be declared abstract.
public abstract void print();
public abstract object larger(object, object);
abstract void insert(int insertItem);
Abstract Classes

• A class that is declared with the reserved word abstract in


its heading.
• An abstract class can contain instance variables,
constructors, finalizers, and non-abstract methods.
• An abstract class can contain abstract methods.
• If a class contains an abstract method, the class must be
declared abstract.
• You can instantiate an object of a subclass of an abstract
class, but only if the subclass gives the definitions of all
the abstract methods of the superclass.
Abstract Class Example

public abstract class AbstractClassExample


{
protected int x;
public abstract void print();

public void setX(int a)


{
x = a;
}

public AbstractClassExample()
{
x = 0;
}
}
abstract class Shape{
public static float pi = 3.142f; protected float height; protected float
width; abstract float area() ;}
class Square extends Shape{
Square(float h, float w){height = h; width = w;}
final float area(){return height * width;}}
class FinalMethodDemo
{
public static void main(String args[])
{
Square sObj = new Square(5,5);

System.out.println("Area of square : " + sObj.area());


}
}
class A
{void get()
{ System.out.println("A"); }}
class B extends A
{
void get()
{ System.out.println("B"); }}
class C
{public static void main(String ar[])
{A obj= new B();
obj.get();
}}
Output?
Lets Do It
• Create a class shape with abstract method of following
signature
abstract double area()
• Create Rectangle and Square two subclasses of shape with
required fields and overridden area method.
• Write a test program to calculate area of square and rectangle
by using methods of above classes.
 Final Classes
• You can declare some or all of a class's methods final. You use
the final keyword in a method declaration to indicate that the
method cannot be overridden by subclasses.
• A final class cannot be subclassed. This is done for reasons of
security and efficiency. Accordingly, many of the Java
standard library classes are final.
• A final class implicitly has all the methods as final, but not
necessarily the data members.
• The Object class does this—a number of its methods are final.
Syntax:
public final class MyFinalClass {...}
public final class FinalClass
{
void meth()
{
System.out.println("Printed in FinalClass.");
}
}
public class SubClass extends FinalClass
{
    public static void main(String[] args)
{
  System.out.println("Printed in SubClass.");
    }
}
 Final Methods
• A final method can't be overridden by subclasses. This is used
to prevent unexpected behavior from a subclass altering a
method that may be crucial to the function or consistency of
the class.
Example
public class MyClass
{
public final void myFinalMethod() {...}
}

You might also like