Sunday, July 12, 2009

Java Class inheritance?

Help? In the first chapter of my textbook it talks about class inheritance, and one of the projects at the end is to create a system of class inheritance for a chess set. Problem is I don't understand how a class inherits from another. I understand how objects inherit from their parent class, but not how one class inherits from another. And to further the problem, the preceding chapter does not have one example of code where a class inherits from another. All it has is a bunch of flowcharts showing class B under class A, and class C under class B. Can someone please explain how classes inherit from each other? Keeping in mind that I'm in the first chapter?

Java Class inheritance?
When a class inherits from another in Java it is said to extend that class. The main class is called parent or 'Superclass' or Base class.





Using an example from the Sun tutorial this is what the Child class or inheriting or 'Subclass' would look like





class MountainBike extends Bicycle


{


// fields and methods defining a mountain bike would go here


}





You can check out the full tutorial here which goes into greater depth


http://java.sun.com/docs/books/tutorial/...





In java you are not allowed multiple inheritance. This is for program consistency reasons. To cut a long story short that means a subclass can only inherit from one class. The way java gets around this is the use of interfaces, ie. allowing classes to use the methods of other classes. A good example of that is this example of a Handyperson specialization that inherits methods from other classes


http://www.leepoint.net/notes-java/oop/i...

online survey

No comments:

Post a Comment