Google Search

Search Results

There was an error in this gadget

Monday, January 14, 2008

Super

Have you ever wonder can we call super class constructor from subclass?It is possible with the keyword super.

Super keyword has two uses.

  • The first is the call to the super class constructor from subclass constructor
  • The second usage is to access a member of the superclass that has been overridden by a subclass
  • A subclass constructor can call a constructor defined in its immediate superclass by employing the following form of super:

- super( parameter list);

Here parameter list specifies any parameters needed by the constructor in the superclass.

Using super to call superclass constructors

  • super() must always be the first statement executed inside a subclass constructor.
  • It clearly tells you the order of invocation of constructors in a class hierarchy.
  • Constructors are invoked in the order of their derivation.
  • A more efficient and robust definition of the superclass RectangularSolid class and the corresponding changes in the subclass RectangularSolidWeight follows.

class RectangularSolid{
private double width;
private double height;
private double depth;


RectangularSolid(double w,double h,double d)
{
width=w;
height=h;
depth=d;
}
RectangularSolid(double length)
{
width=height=depth=length;
}
RectangularSolid()
{
width=height=depth=10;
}

double volume(){
return width*height*depth;
}
}
class RectangularSolidWeight extends RectangularSolid
{
double weight;

public RectangularSolidWeight(double w,double h, double d,double wt)
{
super(w,h,d);
weight = wt;
}
public RectangularSolidWeight(double len,double wt)
{
super(len);
weight = wt;
}
public RectangularSolidWeight()
{
super();
weight =0;
}
}

class SuperDemo
{
public static void main(String[] args)
{
RectangularSolidWeight rsw1 = new RectangularSolidWeight(4,5,7,8.0);
RectangularSolidWeight rsw2 = new RectangularSolidWeight();
RectangularSolidWeight rswcube = new RectangularSolidWeight(3,2);

double volume;
volume = rsw1.volume();
System.out.println("Volume of rsw1 is"+volume);
System.out.println("weight of rsw1 is"+rsw1.weight);
System.out.println();


volume = rsw2.volume();
System.out.println("Volume of rsw2 is"+volume);
System.out.println("weight of rsw2 is"+rsw2.weight);

System.out.println();

volume = rswcube.volume();
System.out.println("Volume of rswcube is"+volume);
System.out.println("weight of rswcube is"+rswcube.weight);
System.out.println();

}
}

Output:

Volume of rsw1 is140.0

weight of rsw1 is8.0

Volume of rsw2 is1000.0

weight of rsw2 is0.0

Volume of rswcube is27.0

weight of rswcube is2.0

The superclass constructor is invoked first followed by the invocation of the subclass constructor.

  • When a subclass calls super(),it is calling the constructor of it immediate superclass
  • This is true even in a multileveled hierarchy
  • super() must always be the first statement inside s subclass constructor.

Thursday, January 10, 2008

Multiple Inheritence

Those who are familiar with C++ might mistaken that JAVA being object oriented also supports multiple inheritance but no, Java supports only single inheritance!

Example:

class A{
}
class B{
}
class C extends B,A{
}

A class cannot extend more than one class. That means one parent per class. A
class can have multiple ancestors, however, since class B could extend class A, and
class C could extend class B, and so on. So any given class might have multiple
classes up its inheritance tree, but that's not the same as saying a class directly
extends two classes. That means a class can have only one immediate
superclass.

The reason that Java's creators chose not to allow multiple inheritance is that it can become quite messy. In a nutshell, the problem is that if a class extended two other classes,and both superclasses had, say, a doStuff() method, which version of doStuff()
would the subclass inherit? This issue can lead to a scenario known as the "Deadly Diamond of Death," because of the shape of the class diagram that can be created in a multiple inheritance design. The diamond is formed when classes B and C both extend A, and both B and C inherit a method from A. If class D extends both B and C, and both B and C have overridden the method in A, class D has, in theory, inherited two different implementations of the same method. Drawn as a class diagram, the shape of the four classes looks like a diamond.

A Superclass Reference Variable Can Reference a Subclass Object

A reference variable of type superclass can be assigned a reference to any subclass object derived from that superclass

class RectangularSolid
{
double width;
double height;
double depth;


RectangularSolid()
{
width=height=depth=10;
}

double volume()
{
return width*height*depth;
}
}

class RectangularSolidWeight extends RectangularSolid
{
double weight;

public RectangularSolidWeight(double w,double h, double d,double wt)
{
width = w;
height = h;
depth = d;
weight = wt;
}
}
class SuperRefDemo
{
public static void main(String[] args)
{
RectangularSolidWeight rsw = new RectangularSolidWeight(4,5,7,8.0);
RectangularSolid rs = new RectangularSolid();
double volume;
volume = rsw.volume();
System.out.println("Volume of rsw is"+volume);
System.out.println("weight of rsw is"+rsw.weight);

rs = rsw;
volume = rs.volume();

System.out.println("Volume of rs is"+volume);

/* weight is a property of child class and superclass reference cannot access child class properties */
System.out.println("weight of rsw is"+rs.weight);
rs = rsw;
volume = rs.volume();

}
}


Think!
Should the following line of code result in computation of volume on superclass object since the invocation of volume methods is apparently on the superclass reference
OR
Should it result in a computation of the volume on the subclass object since the superclass reference variable is referencing a subclass object
  • Method calls in Java are resolved dynamically at runtime
  • In Java all variables know their dynamic type
  • Messages(method calls) are always bound to methods on the basis of the dynamic type of the receiver.
  • This method resolution is done dynamically at runtime.

This holds true for all situations particularly the case when a method is invoked on a superclass reference after having initialized the superclass reference variable with the reference of a subclass object. We therefore reach an important conclusion. It operates on the superclass object in case the superclass reference variable references a superclass object, and it operates on a subclass object in the event of the superclass reference variable containing a reference to a subclass object .This binding of a method to an object is done dynamically at runtime.

The only exception in the java language where method calls are resolved at compile time is in the case of final methods, which we will cover later in the session.

Accessing Superclass Members from subclass Object

A subclass includes all of the members of its superclass

But, it cannot directly access those members of the superclass that have been declared as private.

class A
{
int money;
private int pocketMoney;

void fill(int money,int pocketMoney){

this.money = money;
this.pocketMoney =pocketMoney;
}
}

class B extends A
{
int total;

void sum(){

total = money +pocketMoney; //this will result in copilation error as pocketMoney is private member in class A


}
}

class AccessDemo
{
public static void main(String[] args)
{
B subob = new B();
subob.fill(10,12);
subob.sum();
System.out.println("Total :"+subob.total);
}
}

A Possible Solution to the program

class A
{
int money;
private int pocketMoney;

void fill(int money,int pocketMoney){

this.money = money;
this.pocketMoney =pocketMoney;
}

public int getPocketMoney()
{
return pocketMoney; // its job is to return private data
}
}

class B extends A
{
int total;

void sum(){

total = money +pocketMoney; //this will result in copilation error as pocketMoney is private member in class A


}
}

class AccessDemo
{
public static void main(String[] args)
{
B subob = new B();
subob.fill(10,12);
subob.sum();
System.out.println("Total :"+subob.total);
}
}

References

The only way to access an object is through a reference variable, and there are a few key things to remember about references:

  • A reference variable can be of only one type, and once declared, that type can never be changed (although the object it references can change).To understand this better look at the below example

    class B{
    void add(){
    System.out.println("in class b");
    }
    }

class C extends B{
void sub(){
System.out.println("in class c");
}
}

class RefDemo {
public static void main(String[] args) {
System.out.println("Hello World!");
B b= new B();
/*A reference variable can be of only one type, and once declared, that
type can never be changed*/
C b = new C();/* compilation error b is already defined*/
b.add();
b.sub();
}
}

  • A reference is a variable, so it can be reassigned to other objects, (unless the reference is declared final).

    In reference to above example


    class RefDemo
    {
    public static void main(String[] args)
    {
    System.out.println("Hello World!");
    B b;
    b = new B();
    b.add();

    // A reference is a variable, so it can be reassigned to other objects
    b = new C();
    b.add();
    }
    }

  • If the reference is defined as final it cannot be reassigned to other objects look below example for more clarification

    class refdemo
    {
    public static void main(String[] args)
    {
    System.out.println("Hello World!");

    final B b;
    b = new B();
    b.add();

    b = new C(); /*This code results in compilation error as b is defined as
    final it cannot be reassigned to other objects

    b.add();
    }
    }

  • A reference variable's type determines the methods that can be invoked on the object the variable is referencing.


    class RefDemo
    {
    public static void main(String[] args)
    {
    System.out.println("Hello World!");
    B b;
    b = new B();
    b.add();
    // A reference is a variable, so it can be reassigned to other objects
    b = new C();
    b.add();
    }
    }

    In the above example b is of type B and referring to C object so the method that can be invoked is add() only but not the method sub() even though it is in C object.
    Since child class can inherit properties of parent class but vice versa is not true
    i.e., B reference cannot access C class methods since C is a child of B.

  • A reference variable can refer to any object of the same type as the declared reference, or this is the big one , it can refer to any subtype of the declared type!

    As in above example reference variable of B referring to class C subtype of B.
  • A reference variable can be declared as a class type or an interface type. If the variable is declared as an interface type, it can reference any object of any class that implements the interface.

Generalization/Specialization

  • In keeping with java terminology, a class that is inherited is referred to as a superclass.
  • The class that does the inheriting is referred to as the subclass.
  • Each instance of a subclass includes all members of the superclass.
  • The subclass inherits all the properties of its superclass.

Therefore, the subclass has large set of properties than its superclass. However, a subclass may override some of the properties of its superclass.

Java’s Inheritance Model

  1. Java uses the single inheritance model
  2. In single inheritance, a subclass can inherit from one and only one superclass
  3. Code Syntax for inheritance: class derived class name extends base-class name

To define a new class from an already existing class, you incorporate the definition of an already existing class into the class to be defined by using the extends keyword.

Inheritance – An Example

class A
{
int m,n;
void display1(){
System.out.println("m and n are" + m + " " + n);
}
}

class B extends A
{
int c;
void display2(){
System.out.println("c:" + c);
}
void sum(){
System.out.println("m+n+c = "+(m+n+c));
}
}



class InheritanceDemo
{
public static void main(String[] args)
{
A s1 = new A();
B s2 = new B();
s1.m = 10;
s1.n = 20;
System.out.println("State of object A:");
s1.display1();
s2.m = 7;
s2.n = 8;
s2.c = 9;
System.out.println("State of object B:");
s2.display1();
s2.display2();
System.out.println("Sum of m,n and c in object B is:");
s2.sum();

}
}

Output

State of object A:
m and n are10 20
State of object B:
m and n are7 8
c:9
Sum of m,n and c in object B is:
m+n+c = 24

It is obvious that an object of subclass B includes all of the members of its superclass A. This is why s2 can access a and b and call display1(). Also, inside sum(),a and b can be referred to directly, as if they were part of B.Even though A is a superclass for B, it is also a completely independent, standalone class . Being a superclass for a subclass does not imply that a superclass cannot be used by itself. A subclass can inturn be a superclass for another subclass.

Inheritance

· Inheritance is one of the cornerstones of OOP because it allows for the creation of
hierarchical classifications
· Using inheritance, you can create a general class at top
· This class may then be inherited by other, more specific classes.
· Each of these classes will add only those attributes and behaviors that are unique to it.

A general class is one that defines traits common to a set of related objects, i.e, objects with common attributes and behaviors.

Inheritance leads to the definition of generalized classes that are at the top of an inheritance hierarchy. Inheritance is thus the implementation of generalization. Inheritance, in an object-oriented language like java makes the data and methods of a superclass available to its subclass. Inheritance has many advantages, the most important of them being the reusability of code. Once a class has been created, it can be used to create new subclasses.