This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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 Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "interesting question" Watch "interesting question" New topic

interesting question

Pashi Soni

Joined: Feb 27, 2003
Posts: 26
There is one class
class A{
class B extends 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

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.
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
subject: interesting question
Similar Threads
... if code defines an is-a relationship
How can I get access to methods in other classes
Java Inheritance...
memory issues