• 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
  • Liutauras Vilda
  • Tim Cooke
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Devaka Cooray
  • Ron McLeod
  • paul wheaton
Saloon Keepers:
  • Tim Moores
  • Piet Souris
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Frits Walraven
  • Scott Selikoff

Sub Class

 
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
package sam;

class A{
int a=1;
public void AA(){
System.out.println("AA");
}
}
class B extends A{
int a=2;
public void AA(){
System.out.println("BAA");
}
}


class Form{
public static void main(String args[]){

A sup = new B();
sup.AA();
System.out.println("A:"+sup.a);
}
}
--------------------------------------------------------------
output is : BAA A:1

Why it's printing A=1 instant of A:2
Because its calling the method in subclass.

Thanks in Advance.
 
Ranch Hand
Posts: 332
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Only non-static methods are polymorphic. All other members are resolved at compile-time based on type of the reference.
 
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is called variable shadowing, and has some nonintuitive rules associated with it. Basically what has happened is that by saying

A sup = new B();

you've cast the child object to the parent reference. In this case, the reference doesn't know anything about the variable named "a" in the child class.

The method call is straight forward method overriding.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic