• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

interesting question

 
Pashi Soni
Greenhorn
Posts: 26
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is one class
class A{
a()
{}
}
class B extends A
{
a()
{}
}
method a() is overridden.
class C{

B b = new B()
// here I want to access method a() of class A with the object "b" without instantiating the class A
}
 
Joel McNary
Bartender
Posts: 1824
Eclipse IDE Java Ruby
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The short answer is that you can't do it. The longer answer is that you shouldn't do it. Here's why:
Say you had a class Mammal that had a "giveBirth()" method. This method was defined to create an offspring object by producing live young. Then you had a "Monotreme" class that extended Mammal and overrode "giveBirth()" Instead of live young, monotremes lay eggs. Now you have a pregnant Platypus (Platypus is a sub class of Monotreme, and the isPregnant flag is set to true ). Calling "giveBirth()" on that object should have the result of laying eggs, not birthing live young. You should not be able to call the Mammal's method because the Designer of the classes has decreed that, for Monotremes, giveBirth() shall be accomplished through laying eggs.
On the other hand, you can access the super class's methods from within the subclass. We once again have our Mammal class and its giveBirth() method. Now we create a Marsupial subclass and override giveBirth() as follows:

This method calls the Mammal's "giveBirth()" method (the "super.giveBirth() call) to create the offspring and then puts the offspring into a pouch. This is indirect access to the Mammal's giveBirth() method, but an external class still should not be allowed to just call the Mammal's giveBirth() method (without being in a pouch, the child will die).
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic