• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Benefits of Reference Type

 
Sid Robin
Ranch Hand
Posts: 53
  • 0
  • 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
  • 0
  • 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
  • 0
  • 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
  • 0
  • 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 ?
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic