wood burning stoves 2.0*
The moose likes Java in General and the fly likes interesting question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "interesting question" Watch "interesting question" New topic
Author

interesting question

Pashi Soni
Greenhorn

Joined: Feb 27, 2003
Posts: 26
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

Joined: Aug 20, 2001
Posts: 1817

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).


Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: interesting question