Menus

Jul 25, 2016

Java Inheritance, method overriding, visibility control

Course Contents:
  1. Reference
  2. Super and sub class
  3. Multilevel hierarchy
  4. Method overriding
  5. Dynamic method dispatching
  6. Abstract class


Inheritance
The process of deriving a new class from an old one is called inheritance or derivation. The oldclass is referred to as the base class or super class or parent class and new one is called the derived class or subclass or child class. 

The derived class inherits some or all of the properties from the base class. A class can inherit properties from more than one class or from more than one level. The main purpose of derivation or inheritance is reusability. Java strongly supports the concept of reusability. 

The Java classes can be reused in several ways. Once a class has been written and tested, it can be used by another by another class by inheriting the properties of parent class.

Defining a subclass

A subclass can be defined as follows:
class subclassname extends superclassname
{
 Variable declaration;
 Method declaration;
}
The keyword extends signifies that the properties of the superclassname are extended to the subclassname. 


The subclass will now contain its own variables and methods as well those of the superclass. This kind of situation occurs when we want to add some more properties to an existing class without actually modifying it.

Types of inheritance
The following kinds of inheritance are there in java.
  1. Simple Inheritance
  2. Multilevel Inheritance

Simple Inheritance

Pictorial Representation of Simple Inheritance

When a subclass is derived simply from it's parent class then this mechanism is known as simple inheritance or (a parent class with only one child class is known as single inheritance). 

In case of simple inheritance there is only one subclass and it's parent class. It is also called single inheritance or one level inheritance.
Eg.
class Parent
{
 int x;
 int y;
void get(int p, int q)
{
 x=p; y=q;
}
void Show()
{
 System.out.println("x=" +x + " and y= " +y);
}
}

class Child extends Parent
{
 public static void main(String args[])
 {
 Parent p = new Parent();
 p.get(5,6);
 p.Show();

 }
 }


Subclass constructor
A subclass constructor is used to construct the instance variables of both the subclass and the superclass. The subclass constructor uses the keyword super to invoke the constructor method of the superclass. 

The keyword super is used as:
- Super may only be used within a subclass constructor method.
- The call to superclass constructor must appear as the first statement within the subclass constructor.
- The parameters in the super call must match the order and type of the instance variable declared in the superclass.
Eg.

WAP that demonstrate the use of the keyword super
class Room
{
 int length;
 int breadth;
 Room(int x, int y)
 {
 length= x;
 breadth = y;
 }
 int area()
 {
 return(length*breadth);
 }
 }

class BedRoom extends Room
{
 int height;
 BedRoom(int x, int y, int z)
 {
 super(x,y);//call the superclass constructor with value x and y
 height = z;
 }
 int volume()
 {
 return(length*breadth*height);
 }
}

class SuperTest
{
 public static void main(String args[])
 {
 BedRoom room1 = new BedRoom(2,3,4);//call subclass constructor
 int area1 = room1.area();//superclass method
 int volume1 = room1.volume();//call subclass method
 System.out.println("Area of the room is= " +area1);
 System.out.println("Volume of the bedroom is = " +volume1);
 }
 }

Multilevel 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 levels.
 
Pictorial Representation of Simple and Multilevel Inheritance


Multilevel Inheritance
A derived class with multilevel base classes is declared as follows:
Class vehicle
{
 Instance variables;
 Methods;
}

Class Car extends Vehicle//first level
{
 Instance variables;
 Methods;
 …………..
 …………..
}

Class RacingCar extends Car//second level
{
 Instance variables;
 Methods;
 ……………..
 ……………..
}

WAP that demonstrate the concept of multilevel inheritance
class Student
{
 int roll_number;
 Student(int x)
 {
 roll_number = x;
 }
 void put_number()
 {
 System.out.println("Roll number = " +roll_number);
 } 
}

class Test extends Student
{
 double sub1;
 double sub2;
 Test(int a, double b, double c)
 {
 super(a);
 sub1 = b;
 sub2 = c;
 }
 void put_marks()
 {
 System.out.println("Marks in subject first is = " +sub1);
 System.out.println("Marks in subject second is = " +sub2);
 } 
}


class Result extends Test
{
 double total;
 Result(int a, double b, double c)
 {
 super(a,b,c);
 }
 void display()
 {
 total = sub1 +sub2;
 put_number();
 put_marks();
 System.out.println("Total marks = " +total);
 }
}

class MultiLevelDemo
{
 public static void main(String args[])
 {
 Result Ram = new Result(5,55.5,67.5);
 Ram.display(); 
 } 
}

Method overriding
When a method is defined in subclass that has same name, same arguments and same return type as a method in the superclas and when that method is called, the method defined in the cubclass is invoked and executed instead of the one in superclass. This is known as method overriding.
That is the subclass method override the superclass method.

WAP that demonstrate the concept of method overriding
class A
{
 int i,j;
 A(int x, int y)
 {
 i = x;
 j = y;
 }
 void display()
 {
 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; 
 }
 void display()
 {
 System.out.println (" k = " +k);
 }
}

class MethodOverride
 public static void main(String args[])
 {
 B b1 = new B(2,3,4);// call constructor in class Bs
 b1.display();// this call method in B
 }
}

Output:
K=4

In the above example, when the display() method is called with an object of type B, the version of display() defined in B is executed. That is, the version of display() in B overrides the version in superclass A.
If we need to access the superclass version of an overridden function, we have to use super.

class A
{
 int i,j;
 A(int x, int y)
 {
 i = x;
 j = y;
 }
 void display()
 {
 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; 
 }
 void display()
 {
 super.display();//call display method in A
 System.out.println (" k = " +k); 
 }
}

class MethodOverrideDemo
{
 public static void main(String args[])
 {
 B b1 = new B(2,3,4);// call constructor in class B
 b1.display();// this call method in B
 }
}

Output
I and j = 2 3
K = 4

Dynamic memory dispatch
Dynamic memory dispatch is a mechanism by which a call to an overridden method is resolved at runtime. 

Since in Java, a superclass reference variable can refer to a subclass object. Java uses this fact to resolve calls to overridden methods at runtime. When an overridden method is called through a superclass reference, java determines which version of that method to execute based upon the type of the object being referred to at the time the call occurs.

When different types of objects are referred to, different versions of an overridden method will be called. Dynamic memory dispatch is important because this is how java implements run-time polymorphism.

WAP that demonstrate the concept of dynamic memory dispatch
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 object A
 r.callme();//call A's version of callme
 r = b;//r refers to B object
 r.callme();//call B's version of callme
 r = c;//r refers to C object
 r.callme();//call C's verion of callme
 }
}

Output
Inside A's callme method
Inside B's callme method
Inside C's callme method

final variable and methods
All methods and variables can be overridden by default in subclass. If we wish to prevent the subclasses from overriding the members of the superclass, we can declare them as final using the keyword final as a modifier.

Syntax:
final type variable_name;
final int num=10;
final return_type methodname(){…………}
final void show(){…………….}

Final classes
The class that is declared as final is known as final class. When a class is declared as final, we cannot inherit such class that is we cannot create subclass of such class. Any attempt to inherit these classes will cause an error and the compiler will not allow it. Declaring a class as final implicitly declares all of its method as final.

Syntax:
final class A
{
 ………;
 …………
}
Class B extends A// error cannot subclass A
{
}

Abstract class
Any class that is declared as abstract is known as abstract class. Any class that contains one or more abstract methods must also be declared abstract. The general syntax of the abstract class is:
Abstract class classname
{
 ………
 ……….
 Abstract type methodname(par ameterlist);

}
Eg.
Abstract class shape//abstract class declaration
{
 …………
 …………
 Abstract void draw();// abstract method declaration

}

The abstract class has following properties:
- We cannot create instance of the abstract class using new operator. For example
shape a = new shape();
is illegal because shape is an abstract class.
- The abstract methods of an abstract class must be defined in its subclass
- We cannot declare abstract constructor or abstract static methods
-Any subclass of an abstract class must either implement all of the abstract methods in the superclass, or be itself declared abstract.

WAP that demonstrate the concept of abstract methods and class
abstract class Figure
{
 double dim1;
 double dim2;
 Figure(double a, double b)
 {
 dim1 =a;
 dim2 =b;
 }
 // area is now an abstract method
 abstract double area();
}

class Rectangle extends Figure
{
 Rectangle(double a, double b)
 {
 super(a,b);
 }
 double area()
 {
 System.out.println("Inside area for the Rectangle");
 return(dim1*dim2);
 } 
}

class Triangle extends Figure
{
 Triangle(double x, double y)
 {
 super(x,y); 
 }
 double area()//
 {
 System.out.println("Inside area for the Triangle");
 return((dim1*dim2)/2);
 }
}

class AbstractAreas
{
 public static void main(String args[])
 {
 //Figure f = new Figure(15,15);//illegal
 Rectangle r = new Rectangle(3,4);
 Triangle t = new Triangle(10,10);
 Figure figref;
 figref = r;
 System.out.println("Area is " +figref.area());
 figref = t;
 System.out.println("Area is " +figref.area());
 }
}


Visibility control
There are mainly three types of visibility control that are used to restrict the access to certain variables and methods from outside the class. The visibility modifiers are also known as access modifiers. They provide different level of protection as described below:

1.   Public Access
Members (Variables or methods) that are declared as public are known as public member of the class. Those members have widest level of visibility. Those members that are declared as public can have access from same class, subclass in same package, other classes in same package, subclass in other packages and non-subclasses in other packages.

Syntax:
Public type variablename;
Public type methodname(arglist){……………..}

2.   Protected Access
Members that are declared as protected are known as protected members. The protected modifier makes the fields visible not only to all classes and subclasses in the same package but also to subclasses in other packages. Protected members are not accessible from non-subclasses in other packages.

3.   Private Access
Members that are declared as private are known as private members. The private modifier makes field visible only within their own class. They cannot be inherited by subclasses and therefore not accessible in subclasses.

Access modifier
Public
Protected
Private
No-modifier
Access location




Same class
Yes
Yes
Yes
Yes
Subclass in same package
Yes
Yes
No
Yes
Other class in same package
Yes
Yes
No
Yes
Subclass in other package
Yes
Yes
No
No
Non-subclass in other package
Yes
No
No
No


Fig: visibility of field in a class

1 comment:

Contact Form

Name

Email *

Message *