Showing posts with label Inheritance. Show all posts
Showing posts with label Inheritance. Show all posts

17.Method Overriding

Saturday, February 20, 2010 Posted by Sudarsan 1 comments
Hay, folks in this section we are going to learn “super” keyword and the “Overriding” concepts. So let’s get started!!!

super keyword

We have seen method overloading in the previous posts, as we know that it is the concept of polymorphisam, more precisely we can say that, we can write identical methods with identical method signatures in a same class. At the same way a subclass can also explicitly call a constructor of its immediate superclass. This is done by using the super constructor call. A super constructor call in the constructor of a
subclass will result in the execution of relevant constructor from the superclass, based onthe arguments passed.

For example, we show an example of a super constructor call. Given the following code for Employee.

//Demonstration of Super Key word

/**
 *
 * @author Administrator
 */
// super class Employee
class Employee
{
    String name;
    char sex;
    
    Employee(String n,char s)
    {
        name=n;
        sex=s;
    }

    public String getName()
    {
        return name;
    }

    public char getSex()
    {
        return sex;
    }
}

// sub class Worker
class Worker extends Employee
{
    char cat;
    boolean allow;

    Worker(String n,char s,char c,boolean d)
    {
        super(n,s);  // calling super class Employee Constructor
        cat=c;
        allow=d;
    }

    public char getCat()
    {
        return cat;
    }

    public boolean getAll()
    {
        return allow;
    }
}

// subclass Officer

class Officer extends Employee
{
    char empclass;
    int exp;
    boolean veh;

    Officer(String n,char s,char c,int e,boolean v)
    {
        super(n,s); // Calling super class Worker Constructor
        empclass=c;
        exp=e;
        veh=v;

    }

    public char getEmpClass()
    {
        return empclass;
    }

    public int getExp()
    {
        return exp;
    }
    public boolean getVehicale()
    {
        return veh;
    }
}
// Main Class

public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        //Constructing and calling Worker Object and its methods

        Worker w=new Worker("Sudarsn",'M','B',true);

        System.out.println("Worker Information");
        System.out.println("Name :"+w.getName());
        System.out.println("Sex :"+w.getSex());
        System.out.println("Category : "+w.getCat());

        if(w.getAll())
        {
            System.out.println("Dress allowance is paid");
        }
        else
        {
            System.out.println("Dress allowance is not paid");
        }

        // Constructing Officer Object and calling its methods
        Officer o=new Officer("Raghu",'M','I',15,true);

        System.out.println("\nOfficer Information");

        System.out.println("Name :"+o.getName());
        System.out.println("Sex : "+o.getSex());
        System.out.println("Class :"+o.getEmpClass());
        System.out.println("Experiance :"+o.getExp());

        if(o.getVehicale())
        {
            System.out.println("Vehical is provided");
        }
        else
        {
            System.out.println("Vechical is not provided");
        }
    }

}

From the above example we can observe that the code calls the default constructor of its immediate superclass and executes it.

If we compile the above program we can see the fallowing output.

Worker Information
Name :Sudarsn
Sex :M
Category : B
Dress allowance is paid

Officer Information
Name :Raghu
Sex : M
Class :I
Experiance :15
Vehical is provided

There are a few things to remember when using the super constructor call:

1. The super() call MUST OCCUR THE FIRST STATEMENT IN A CONSTRUCTOR.
2. The super() call can only be used in a constructor definition.
3. This implies that the this() construct and the super() calls CANNOT BOTH OCCUR IN
THE SAME CONSTRUCTOR.

Another use of super is to refer to members of the superclass (just like the this keyword).

The usage has the fallowing general form

super.member

For example,

//Demonstartion of name hiding

/**
 *
 * @author Administrator
 */

class A
{
    int i;

}

//Sub Class B

class B extends A
{
    int i;

    B(int a,int b)
    {
        super.i=a;  // i in Class A
        i=b;        // Refers i in Class B
    }

    void display()
    {
        System.out.println("I in Super Class : "+super.i);
        System.out.println("I in Sub Class : "+i);
    }
}
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        B ob=new B(10,20);

        ob.display();
    }

}

The second form of super acts somewhat like this keyword, except that it always refers to the super class of the subclass in which it is used.

If we compile the above program we can get the fallowing output.

I in Super Class : 10
I in Sub Class : 20

Overriding Methods

If for some reason a derived class needs to have a different implementation of a certain
method from that of the superclass, overriding methods could prove to be very useful.This is also called Run-Time Ploymorphisam or Dynamic Method Dispatch.

A subclass can override a method defined in its superclass by providing a new
implementation for that method.Suppose we have the following implementation for the display() method in the super class A.

// Dynamic Method Dispatch

/**
 *
 * @author Administrator
 */
class A
{
    void display()
    {
        System.out.println("Inside A's display method");
    }
}

class B extends A
{
    void display()
    {
        System.out.println("Inside B's dispaly method");
    }
}
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        // Constructing Objects for A and B
        A a=new A();
        B b=new B();

        // Obtain a reference of type A
        A r;


        r=a; // Here r refers to an object of A
        r.display();

        r=b;  // r refers to an object of B
        r.display();
    }

}

When we compile the above code we will get the fallowing result
Inside A's display method
Inside B's dispaly method

That’s all for this time! In the next post we will discuss more about further topics in java.
Labels:

15. Inheritance

Thursday, September 10, 2009 Posted by Sudarsan 0 comments
In this post we are going to learn how inheritance promotes software reusability, the notations of superclass and subclass, using extends to create a class that inherits from another class and to use, protected modifier.

Inheritance enables a class to, Inherit data members and methods from another class and also reuse the functionalities and capabilities of the existing class by extending a new class from the existing class and adding new features to it.

Some of the key points which are associated with inheritance are given below.

1. The class that inherits the data members and methods from another class is known as the subclass.

2. The class from which the subclass inherits is known as the superclass.

3. The superclass is also referred to as the base class, and the subclass is referred to as the derived class.

4. We can create additional data members and methods to add more features in a subclass.

5. A superclass can also be a subclass of another class.

The direct superclass of a subclass specified by the keyword extends in the firstline of a class declaration is the superclass from which the subclass inherits.

An indirect superclass of a subclass is two or more levels up the class hierarchy from the subclass.

Implementing Different Types of Inheritance

Single level inheritance:

Derives a subclass from a single superclass. For example, subclasses B and C inherit the properties of a single superclass, A. The following figure shows the structure of single level inheritance.

The following syntax shows how to implement single level inheritance:
class A
{
}
class B extends A
{
}
class C extends A
{
}

In the preceding syntax, the extends keyword is used to derive a subclass from a superclass.

Multilevel inheritance

Inherits the properties of another subclass. For example, Class A is a superclass for the Class B; and Class B is a superclass for the subclass, Class C. You can include any number of levels in multilevel inheritance. The following figure shows the structure of multilevel inheritance:

The following syntax shows how to implement multilevel inheritance
class A
{
}
class B extends A
{
}
class C extends B
{
}

In the preceding syntax, class A is the superclass and class C is the subclass. The class B acts as a subclass for the class A and superclass for the class C.

Note: Java does not support multiple inheritance.

Have a look at the fallowing example to know more about Single Level Inheritance

Example
// Super class Book.java

/**
 *
 * @author SUDARSAN
 */
class Book {

    //Declaring the data members.
    String author= "Steve";
    String title = "Handbook";
    int price = 50;
    int pages = 350;
    int stock = 13;

    //Defining the methods.

 public void show()
 {
  System.out.println(" ");
  System.out.println("\t Books Information");
  System.out.println("\t Book Author: " + author);
  System.out.println("\t Book Title: " + title);
  System.out.println("\t Book Price: " + price);
  System.out.println("\t Number of pages: " + pages);
  System.out.println("\t Book Stock: " + stock);
  System.out.println(" ");
  }
}

// SubClass HardwareBook.java

/**
 *
 * @author SUDARSAN
 */
class HardwareBook extends Book{
    //Declaring the data members.
String hardwareTitle = "Printers";
String publisher = "Tom Wilkins";
//Defining the method, showData()
 public void showData()
 {
  System.out.println(" ");
  System.out.println("\t Hardware Books Information");
  System.out.println("\t Hardware Title: " + hardwareTitle);
  System.out.println("\t Publisher Name: " + publisher);
  System.out.println(" ");
        }

}

// SubClass SoftwareBook.java

/**
 *
 * @author SUDARSAN
 */
class SoftwareBook extends Book{

        //Declaring the data members.
    String softwareName = "Windows";
    String softwareVersion = "Mary Peterson";

        //Definition of method
 public void showDetails()
 {
            //Calling the method of Book class.
            show();
            System.out.println("\t Software Books Information");
            System.out.println("\t Software Name: " + softwareName);
            System.out.println("\t Software Version: " + softwareVersion);
            System.out.println(" ");
 } 
}

//Main Class

/**
 *
 * @author SUDARSAN
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        HardwareBook h = new HardwareBook();
        SoftwareBook s = new SoftwareBook();
        s.showDetails();
        h.showData();
    }

}

If we compile this program we can get the fallowing output

Books Information
Book Author: Steve
Book Title: Handbook
Book Price: 50
Number of pages: 350
Book Stock: 13

Software Books Information
Software Name: Windows
Software Version: Mary Peterson


Hardware Books Information
Hardware Title: Printers
Publisher Name: Tom Wilkins

Example for Multilevel Inheritance
// SuperClass Book.java

/**
 *
 * @author SUDARSAN
 */
class Book {

    //Declaring the data members.
    int price;
    int pages;
    //Defining the get() method.
    public void get(int mprice, int mpages)
    {
 price = mprice;
 pages = mpages;
    }
    public void show()
    {
 System.out.println(" ");
 System.out.println("\t Books Information");
 System.out.println("\t Book Price: " + price);
 System.out.println("\t Number of pages: " + pages);
 System.out.println(" ");

     }

}

// SubClass SoftwareBook.java

/**
 *
 * @author SUDARSAN
 */
class SoftwareBook extends Book{

    //Declaring the data members.
    String softwareName;
    String softwareVersion;

    //Defining the methods.
    
    public void getDetails(String msoftwareName, String msoftwareVersion)
    {
 softwareName = msoftwareName;
 softwareVersion = msoftwareVersion;
    }
    public void showDetails()
    {
 System.out.println(" ");
 System.out.println("\t Software Books Information");
 System.out.println("\t Software Name: " + softwareName);
 System.out.println("\t Software Version: " + softwareVersion);
 System.out.println(" ");
    }

}

// SubClass Cplus.java

/**
 *
 * @author SUDARSAN
 */
class Cplus extends SoftwareBook{

    //Declaring the data members.

    String author;
    String title;

    //Defining the methods.
    public void getData(String mauthor, String mtitle)
    {
 author = mauthor;
 title = mtitle;
    }
    public void showData()
    {
        show();
        showDetails();
 System.out.println(" ");
 System.out.println("\t C++ Books Information");
 System.out.println("\t Author Name: " + author);
 System.out.println("\t Book Title: " + title);
 System.out.println(" ");
    }

}

// Main Class

/**
 *
 * @author SUDARSAN
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        Cplus c = new Cplus();
        c.get(45, 450); // Calling the get() method of the Book class.

        // Calling the getDetails() method of the Software class.
        c.getDetails("Borland C++", "5.0");

        // Calling the getData() method of the Cplus class.
        c.getData("Lee Mitchell", "Programming using C++");
        c.showData();
    }

}

If we compile the above program we can get the fallowing result.

Books Information
Book Price: 45
Number of pages: 450


Software Books Information
Software Name: Borland C++
Software Version: 5.0


C++ Books Information
Author Name: Lee Mitchell
Book Title: Programming using C++

Ok folks, that’s all for today, in the next post we are going to discuss more about inheritance and Overriding concepts, so keep an eye on the next post.
Labels: