• 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

SubClass??

 
Ranch Hand
Posts: 435
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class Super
{
public int getNumber( int a)
{
return 2;
}
}
public class SubClass extends Super
{
public int getNumber( int a, char ch)
{
return 4;
}
public static void main(String[] args)
{
System.out.println( new SubClass().getNumber(4) );
}
}
Ans : 2
I ran the program it gave me the above ans.
But I am confused, since in the main , it is calling the SubClass, it should print 4
Please explain.
Sonir
 
Ranch Hand
Posts: 418
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sohir,
Have a look at method prototype. It is getNumber(int) and not GetNumber(int, char) . so the super class method is called.
HIH
Rashmi
 
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
Can u please explain the use of new statement here.
Are we using it b'coz we are making static reference to method int getNumber(int) in class Super.
Please reply early,
thanx in advance,
Nisheeth
 
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
No, there's no static method being invoked. You're creating a new SubClass object because you want to invoke its getNumber() method. Because getNumber() is NOT static, you can't just call "getNumber()", you can only call it on an actual class instance. That's why the new SubClass() statement is there. This is just a shorthand way of writing
SubClass aSubClassInstance = new SubClass();
System.out.println( aSubClassInstance.getNumber(4) );

Rob
 
reply
    Bookmark Topic Watch Topic
  • New Topic