Saturday, March 9, 2013

Inheritance(IS-A)


Inheritance

In the preceding lessons, you have seen inheritance mentioned several times. In the Java language, classes can be derived from other classes, thereby inheriting fields and methods from those classes.

Definitions: 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).

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.

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, Object. Such a class is said to be descended from all the classes in the inheritance chain stretching back to Object.

The idea of inheritance is simple but powerful: When you want to create a new class and there is already a class that includes some of the code that you want, you can derive your new class from the existing class. In doing this, you can reuse the fields and methods of the existing class without having to write (and debug!) them yourself.
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.

The Java Platform Class Hierarchy

The Object class, defined in the java.lang package, defines and implements behavior common to all classes—including the ones that you write. In the Java platform, many classes derive directly from Object, other classes derive from some of those classes, and so on, forming a hierarchy of classes.


All Classes in the Java Platform are Descendants of Object

At the top of the hierarchy, Object is the most general of all classes. Classes near the bottom of the hierarchy provide more specialized behavior.

An Example of Inheritance

Here is the sample code for a possible implementation of a Bicycle class that was presented in the Classes and Objects lesson:
public class Bicycle {
        
    // the Bicycle class has three fields
    public int cadence;
    public int gear;
    public int speed;
        
    // the Bicycle class has one constructor
    public Bicycle(int startCadence, int startSpeed, int startGear) {
        gear = startGear;
        cadence = startCadence;
        speed = startSpeed;
    }
        
    // the Bicycle class has four methods
    public void setCadence(int newValue) {
        cadence = newValue;
    }
        
    public void setGear(int newValue) {
        gear = newValue;
    }
        
    public void applyBrake(int decrement) {
        speed -= decrement;
    }
        
    public void speedUp(int increment) {
        speed += increment;
    }
        
}
A class declaration for a MountainBike class that is a subclass of Bicycle might look like this:
public class MountainBike extends Bicycle {
        
    // the MountainBike subclass adds one field
    public int seatHeight;
 
    // the MountainBike subclass has one constructor
    public MountainBike(int startHeight,
                        int startCadence,
                        int startSpeed,
                        int startGear) {
        super(startCadence, startSpeed, startGear);
        seatHeight = startHeight;
    }   
        
    // the MountainBike subclass adds one method
    public void setHeight(int newValue) {
        seatHeight = newValue;
    }   
}
MountainBike inherits all the fields and methods of Bicycle and adds the field seatHeight and a method to set it. Except for the constructor, it is as if you had written a new MountainBike class entirely from scratch, with four fields and five methods. However, you didn't have to do all the work. This would be especially valuable if the methods in the Bicycle class were complex and had taken substantial time to debug.

What You Can Do in a Subclass

A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the package-private members of the parent. You can use the inherited members as is, replace them, hide them, or supplement them with new members:
  • The inherited fields can be used directly, just like any other fields.
  • You can declare a field in the subclass with the same name as the one in the superclass, thus hiding it (not recommended).
  • You can declare new fields in the subclass that are not in the superclass.
  • The inherited methods can be used directly as they are.
  • You can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it.
  • You can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it.
  • You can declare new methods in the subclass that are not in the superclass.
  • You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super.
The following sections in this lesson will expand on these topics.

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.
A nested class has access to all the private members of its enclosing class—both fields and methods. Therefore, a public or protected nested class inherited by a subclass has indirect access to all of the private members of the superclass.

Casting Objects

We have seen that an object is of the data type of the class from which it was instantiated. For example, if we write
public MountainBike myBike = new MountainBike();
then myBike is of type MountainBike.
MountainBike is descended from Bicycle and Object. Therefore, a MountainBike is a Bicycle and is also an Object, and it can be used wherever Bicycle or Objectobjects are called for.
The reverse is not necessarily true: a Bicycle may be a MountainBike, but it isn't necessarily. Similarly, an Object may be a Bicycle or a MountainBike, but it isn't necessarily.
Casting shows the use of an object of one type in place of another type, among the objects permitted by inheritance and implementations. For example, if we write
Object obj = new MountainBike();
then obj is both an Object and a MountainBike (until such time as obj is assigned another object that is not a MountainBike). This is called implicit casting.
If, on the other hand, we write
MountainBike myBike = obj;
we would get a compile-time error because obj is not known to the compiler to be a MountainBike. However, we can tell the compiler that we promise to assign aMountainBike to obj by explicit casting:
MountainBike myBike = (MountainBike)obj;
This cast inserts a runtime check that obj is assigned a MountainBike so that the compiler can safely assume that obj is a MountainBike. If obj is not a MountainBike at runtime, an exception will be thrown.

Note: You can make a logical test as to the type of a particular object using the instanceof operator. This can save you from a runtime error owing to an improper cast. For example:
if (obj instanceof MountainBike) {
    MountainBike myBike = (MountainBike)obj;
}
Here the instanceof operator verifies that obj refers to a MountainBike so that we can make the cast with knowledge that there will be no runtime exception thrown.

this keyword


this keyword in Java is a special keyword which can be used to represent current object or instance of any  class in Java. “this” keyword can also call constructor of same class in Java and used to call overloaded constructor. In this Java tutorial we will see how to use this keyword in Java  and
different examples of this in Java. this sometime also associate with super keyword which is used to denote instance of super class in Java and can be used to call overloaded constructor in Java.

this keyword in Java
Important points about this keyword in Java
here are few important points related to using this keyword in Java.
1) this keyword represent current instance of class.

2) You can synchronize on this in synchronizedblock in Java

synchronized(this){
//this synchronized block will be locked on current instance
}

3) this keyword can be used to call overloadedconstructor in java. if used than it must be first statement in constructor this() will call no argument constructor and this(parameter) will call one argument constructor with appropriate parameter. here is an example of using this() for constructor chaining:

Example of this keyword to call constructor in Java

class Loan{
    private double interest;
    private String type;
  
    public Loan(){
       this(“personal loan”);
    }
  
    public Loan(String type){
        this.type = type;
        this.interest = 0.0;
    }  
}

4) If member variable and local variable name conflict than this can be used to refer member variable.
here is an example of this with member variable:

  public Loan(String type, double interest){
        this.type = type;
        this.interest = interest;
  }

Here local variable interest and member variable interest conflict which is easily resolve by referring member variable as this.interest
5) this is a final variablein Java and you can not assign value to this. this will result in compilation
error:

this = new Loan(); //cannot assign value to final variable : this

6) you can call methods of class by using this keyword as shown in below example.
   
   public String getName(){
        return this.toString();
    }

7) this can be used to return object. this is a valid return value. here is an example of using as return value.

public Loan getLoan(){
 return this;
}

8) this can be used to refer static membersin Java as well but its discouraged and as per best practices
this should be used on non static reference.

9) "this" keyword can not be used in static context i.e. inside static methods or staticinitializer block.
if use this inside static context you will get compilation error as shown in below example:

  public static void main(String args){
       this.toString{}; //compilation error: non static variable this can not be used in static context
  }

10) this can also be passed as method parameters since it represent current object of class.


That’s all on this keyword in Java. You should know about this and super keyword and get yourself familiar with different usage of this keyword in java.




Static Methods and Variables

Static Methods and Variables 

All class instances share the static variables and methods .They are declared using the “static” modifier. The static modifier can be applied to method, variable or a block. All the instances see the changes in the static variable.

Static and non static methods can access the static variables.


Code:
public class Main {

    public static void main(String[] args) {
     
         BMW_H5 car1=new BMW_H5("Owner1");
         BMW_H5 car2=new BMW_H5("Owner2");
       
         System.out.println("Car 1 owner "+car1.getOwnername());
         System.out.println("Car 1 : salary "+car1.getSalary());
         System.out.println("Car 2 owner "+car2.getOwnername());
         System.out.println("Car 2 : salary "+car2.getSalary());
         BMW_H5.setSalary(6999.0f);
           System.out.println("Car 1 owner "+car1.getOwnername());
         System.out.println("Car 1 : salary "+car1.getSalary());
         System.out.println("Car 2 owner "+car2.getOwnername());
         System.out.println("Car 2 : salary "+car2.getSalary());
       
       
    }

}


class BMW_H5
{
    private static float salary=5000.0f;
    private String ownername;
    public BMW_H5(String ownername)
    {
        this.ownername=ownername;
    }
    public static float getSalary() {
        return salary;
    }

    public static void setSalary(float salary) {
        BMW_H5.salary = salary;
    }

    public String getOwnername() {
        return ownername;
    }

    public void setOwnername(String ownername) {
        this.ownername = ownername;
    }
   
 
   
 
   
 
   
 
}


The output of this code is :

Code:
Car 1 owner Owner1
Car 1 : salary 5000.0
Car 2 owner Owner2
Car 2 : salary 5000.0
Car 1 owner Xonwer1
Car 1 : salary 6999.0
Car 2 owner Xonwer2
Car 2 : salary 6999.0

In the code above when i changed the value of static variable "salary", it changed for both .But every one has its own "ownername" variable.

Note : the static variable can be accessed by the class name or the instance of the class.

Same as static variable , the static method is come for all instances of the class. Static method can't access non static methods and variables in the class. Static functions can be called using the class name without the need to create any instance. The most well known example about static methods is the main function which is used to run your java application.


Code:
public class Main {
    public String myname="Tom";

    public static void main(String[] args) {

         System.out.println("myname = "+myname);

    }
}


The code above will not compile ,because the variable myname is not static .

Example on the static block of code :

The following example has a static block of code .


Code:
public class Main {
    public static int x=0;
    static
 
    {
        x++;
        System.out.println("static block  x="+x);
    }
   
           
 
    public static void main(String[] args) {

          Main obj=new Main();
          System.out.println("main function x="+x);

    }
}

The steps is the following :
1 - x is initialized by 0.
2 - static block is executed .


The output of the program :

Code:
static block  x=1
main function x=1


The static block is executed just one ,in the class loading . And not in the creation of an instance.