• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Benefits of Reference Type

 
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 893
Tomcat Server Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What are the benefits when using collections, as I posted here:
https://coderanch.com/t/266667/java-programmer-SCJP/certification/polymorphism ?
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic