• 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:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

method invocation through Inheritance.

 
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi
Can anybody explain me the difference between the following two types of method invocations (1)&(2)?
javascript: x()
banghead


(1)
class BaseClass{
static void sayHello(){
System.out.println("Hi pal!!!, I am BaseClass");
}
}

public class SubClass extends BaseClass{
static void sayHello(){
System.out.println("Hi pal!!!, I am SubClass");
}
public static void main(String [] arg){
BaseClass bc = new SubClass();
bc.sayHello();
}
}

Ans: Hi Pal!!!, I am BaseClass




(2)
class BaseClass{
int x = 10;
public void aMethod(){
System.out.println("x = "+x);
}
}
class SubClass extends BaseClass{
int x = 20;
public void aMethod(){
System.out.println("x = "+x);
}
public static void main(String [] arg){
BaseClass bc = new SubClass();
bc.aMethod();
}
}

Ans: x = 20


Thanks in advance.
 
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Ali,

Welcome to JavaRanch,

Your query comes under frequently asked questions.

Here you go:


Case (1):
One Liner: static methods are not overridden.
In the subclass you redefine the base class method that is not overriding.
It is also called hiding base class method too.
In such a case No Polymorphism (calling subclass method using baseclass reference variable (known as late binding))
Static method selection is done at compile time on behalf of the type of the
reference variable.





Case (2):
It is example of method overriding. The subclass overrides the baseclass method. So polymorphism applies here.
Method selection is done at run time (unlike case 1), on behalf of the object referenced by the reference variable. In our case 3, the at run time the reference variable refers to Subclass object so, subclass version of the method is called.




Regards,
cmbhatt
 
m ali
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Chandra Bhatt.
reply
    Bookmark Topic Watch Topic
  • New Topic