say for example i have 3 classes
public class a
public static void main(String args)
class b extends a
my aim is to call from class a printa() method...
i have two options of doing it by class b and class c as shown...
what would be the best way of doing it...
my call on it is doing using class c...reason--->consider if class a has n number of methods and i want to access only one method...than in such a case why should i have overhead of those n number of methods when i only want to access one....
Originally posted by Srikanth Ramu:
... Basically going for Inheritance or not depends on your broader requirement i.e what you are going to do in Class b and its utility
To expand on the point Srikanth made, your question is about whether to use composition (HAS-A) or inheritance (IS-A). In particular, should your new class have an instance of A, or should your new class be an instance of A? To answer this, we would need to know more about what these classes are intended to represent.
In Thinking in Java, Bruce Eckel suggests...
A general guideline is "Use inheritance to express differences in behavior, and fields to express variations in state."
For a more detailed discussion of this question, see the Designing with inheritance section from TIJ's polymorphism chapter.
Be careful because sometimes inheritance is more attractive than composition (usually, it's easier to implement). However, it's often not the best choice. Particularly, there're two interesting quotes you should have in your mind (well... I do .
"Prefere composition to inheritance" (GoF - Gand of Four)
"Inherit, not to reuse, but to be reused." (Herb Sutter and Andrei Alexandrescu)