This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Benefits of Reference Type

 
Sid Robin
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello every one

class A {

}

class B extends A{

}

class Test {
public static void main(Strings args[]){

A a = new B();//line 1
B b = new B();//line 2
}

}

what are the advantages of using reference type A as in line 1 compared to B

in line 2 . Please explain
 
Hasitha Randika
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi i think you have heard about polymorphysm.

A a = new B(); this is polymorphysm the advantage of this is non static methods when overriding goes to the object type.

class A{
int x = 10;
void m(){
System.out.println("Mike");
}
}
class B extends A{
int x = 20;
void m(){
System.out.println("You");
}
}
class C{
public static void main(String ar[]){
A a = new B();
a.m();
System.out.println(a.x);
}
}

now here the out put will be You
but in second out put will be 10 other than non static methods all the others goes to the Referance type.
 
Remko Strating
Ranch Hand
Posts: 893
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The advantage is that you can write generic code for the superclass in which you can use the specialized behaviour of the subclass
 
Joshua Fix
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What are the benefits when using collections, as I posted here:
http://www.coderanch.com/t/266667/java-programmer-SCJP/certification/polymorphism ?
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic