{"id":405,"date":"2007-10-21T00:00:00","date_gmt":"2007-10-21T00:00:00","guid":{"rendered":"http:\/\/www.strongd.net\/?p=405"},"modified":"2007-10-21T00:00:00","modified_gmt":"2007-10-21T00:00:00","slug":"Inheritance","status":"publish","type":"post","link":"https:\/\/www.strongd.net\/?p=405","title":{"rendered":"Inheritance"},"content":{"rendered":"<p><DIV id=PageTitle>Inheritance<\/DIV><br \/>\n<BLOCKQUOTE><!-- Inheritance -->In the preceding lessons, you have seen <I>inheritance<\/I> mentioned several times. In the Java language, classes can be <I>derived<\/I> from other classes, thereby <I>inheriting<\/I> fields and methods from those classes.<br \/>\n<BLOCKQUOTE><br \/>\n<HR><br \/>\n<STRONG>Definitions:<\/STRONG>&nbsp;<br \/>\n<P>A class that is derived from another class is called a <I>subclass<\/I> (also a <I>derived class<\/I>, <I>extended class<\/I>, or <I>child class<\/I>). The class from which the subclass is derived is called a <I>superclass<\/I> (also a <I>base class<\/I> or a <I>parent class<\/I>). <\/P><br \/>\n<P>Excepting <CODE>Object<\/CODE>, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of <CODE>Object<\/CODE>. <\/P><br \/>\n<P>Classes can be derived from classes that are derived from classes that are derived from classes, and so on, and ultimately derived from the topmost class, <CODE>Object<\/CODE>. Such a class is said to be <I>descended<\/I> from all the classes in the inheritance chain stretching back to <CODE>Object<\/CODE>. <\/P><br \/>\n<HR><br \/>\n<\/BLOCKQUOTE>The idea of inheritance is simple but powerful: When you want to create a new class and there is already a class that includes some of the code that you want, you can derive your new class from the existing class. In doing this, you can reuse the fields and methods of the existing class without having to write (and debug!) them yourself.<br \/>\n<P>A subclass inherits all the <I>members<\/I> (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass. <\/P><br \/>\n<H3 fmstyle=\"C-Head\">The Java Platform Class Hierarchy<\/H3>The <A class=APILink href=\"http:\/\/java.sun.com\/javase\/6\/docs\/api\/java\/lang\/Object.html\" target=_blank><CODE>Object<\/CODE><\/A> class, defined in the <CODE>java.lang<\/CODE> package, defines and implements behavior common to all classes\u2014including the ones that you write. In the Java platform, many classes derive directly from <CODE>Object<\/CODE>, other classes derive from some of those classes, and so on, forming a hierarchy of classes.<br \/>\n<CENTER><br \/>\n<P><IMG height=241 alt=\"All Classes in the Java Platform are Descendants of Object\" src=\"http:\/\/java.sun.com\/docs\/books\/tutorial\/figures\/java\/classes-object.gif\" width=560 align=bottom><\/P><br \/>\n<P class=FigureCaption>All Classes in the Java Platform are Descendants of Object<\/P><\/CENTER>At the top of the hierarchy, <CODE>Object<\/CODE> is the most general of all classes. Classes near the bottom of the hierarchy provide more specialized behavior.<br \/>\n<H3 fmstyle=\"C-Head\">An Example of Inheritance<\/H3>Here is the sample code for a possible implementation of a <CODE>Bicycle<\/CODE> class that was presented in the Classes and Objects lesson:<br \/>\n<BLOCKQUOTE><PRE>public class Bicycle {<\/p>\n<p>    \/\/ <B>the Bicycle class has three <I>fields<\/I><\/B><br \/>\n    public int cadence;<br \/>\n    public int gear;<br \/>\n    public int speed;<\/p>\n<p>    \/\/ <B>the Bicycle class has one <I>constructor<\/I><\/B><br \/>\n    public Bicycle(int startCadence, int startSpeed, int startGear) {<br \/>\n        gear = startGear;<br \/>\n        cadence = startCadence;<br \/>\n        speed = startSpeed;<br \/>\n    }<\/p>\n<p>    \/\/ <B>the Bicycle class has four <I>methods<\/I><\/B><br \/>\n    public void setCadence(int newValue) {<br \/>\n        cadence = newValue;<br \/>\n    }<\/p>\n<p>    public void setGear(int newValue) {<br \/>\n        gear = newValue;<br \/>\n    }<\/p>\n<p>    public void applyBrake(int decrement) {<br \/>\n        speed -= decrement;<br \/>\n    }<\/p>\n<p>    public void speedUp(int increment) {<br \/>\n        speed += increment;<br \/>\n    }<\/p>\n<p>}<br \/>\n<\/PRE><\/BLOCKQUOTE><br \/>\n<P>A class declaration for a <CODE>MountainBike<\/CODE> class that is a subclass of <CODE>Bicycle<\/CODE> might look like this: <\/P><br \/>\n<BLOCKQUOTE><PRE>public class MountainBike extends Bicycle {<\/p>\n<p>    \/\/ <B>the MountainBike subclass adds one <I>field<\/I><\/B><br \/>\n    public int seatHeight;<\/p>\n<p>    \/\/ <B>the MountainBike subclass has one <I>constructor<\/I><\/B><br \/>\n    public MountainBike(int startHeight, int startCadence, int startSpeed, int startGear) {<br \/>\n        super(startCadence, startSpeed, startGear);<br \/>\n        seatHeight = startHeight;<br \/>\n    }\t<\/p>\n<p>    \/\/ <B>the MountainBike subclass adds one <I>method<\/I><\/B><br \/>\n    public void setHeight(int newValue) {<br \/>\n        seatHeight = newValue;<br \/>\n    }\t<\/p>\n<p>}<br \/>\n<\/PRE><\/BLOCKQUOTE><CODE>MountainBike<\/CODE> inherits all the fields and methods of <CODE>Bicycle<\/CODE> and adds the field <CODE>seatHeight<\/CODE> and a method to set it. Except for the constructor, it is as if you had written a new <CODE>MountainBike<\/CODE> class entirely from scratch, with four fields and five methods. However, you didn&#8217;t have to do all the work. This would be especially valuable if the methods in the <CODE>Bicycle<\/CODE> class were complex and had taken substantial time to debug.<br \/>\n<H3 fmstyle=\"C-Head\">What You Can Do in a Subclass<\/H3>A subclass inherits all of the <I>public<\/I> and <I>protected<\/I> members of its parent, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the <I>package-private<\/I> members of the parent. You can use the inherited members as is, replace them, hide them, or supplement them with new members:<br \/>\n<UL><br \/>\n<LI>The inherited fields can be used directly, just like any other fields. <\/LI><br \/>\n<LI>You can declare a field in the subclass with the same name as the one in the superclass, thus <I>hiding<\/I> it (not recommended). <\/LI><br \/>\n<LI>You can declare new fields in the subclass that are not in the superclass. <\/LI><br \/>\n<LI>The inherited methods can be used directly as they are. <\/LI><br \/>\n<LI>You can write a new <I>instance<\/I> method in the subclass that has the same signature as the one in the superclass, thus <I>overriding<\/I> it. <\/LI><br \/>\n<LI>You can write a new <I>static<\/I> method in the subclass that has the same signature as the one in the superclass, thus <I>hiding<\/I> it. <\/LI><br \/>\n<LI>You can declare new methods in the subclass that are not in the superclass. <\/LI><br \/>\n<LI>You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword <CODE>super<\/CODE>. <\/LI><\/UL>The following sections in this lesson will expand on these topics.<br \/>\n<H3 fmstyle=\"C-Head\">Private Members in a Superclass<\/H3>A subclass does not inherit the <CODE>private<\/CODE> members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass.<br \/>\n<P>A nested class has access to all the private members of its enclosing class\u2014both fields and methods. Therefore, a public or protected nested class inherited by a subclass has indirect access to all of the private members of the superclass. <\/P><br \/>\n<H3 fmstyle=\"C-Head\">Casting Objects<\/H3>We have seen that an object is of the data type of the class from which it was instantiated. For example, if we write<br \/>\n<BLOCKQUOTE><PRE>public MountainBike myBike = new MountainBike();<br \/>\n<\/PRE><\/BLOCKQUOTE>then <CODE>myBike<\/CODE> is of type <CODE>MountainBike<\/CODE>.<br \/>\n<P><CODE>MountainBike<\/CODE> is descended from <CODE>Bicycle<\/CODE> and <CODE>Object<\/CODE>. Therefore, a <CODE>MountainBike<\/CODE> is a <CODE>Bicycle<\/CODE> and is also an <CODE>Object<\/CODE>, and it can be used wherever <CODE>Bicycle<\/CODE> or <CODE>Object<\/CODE> objects are called for. <\/P><br \/>\n<P>The reverse is not necessarily true: a <CODE>Bicycle<\/CODE> <I>may be<\/I> a <CODE>MountainBike<\/CODE>, but it isn&#8217;t necessarily. Similarly, an <CODE>Object<\/CODE> <I>may be<\/I> a <CODE>Bicycle<\/CODE> or a <CODE>MountainBike<\/CODE>, but it isn&#8217;t necessarily. <\/P><br \/>\n<P><I>Casting<\/I> shows the use of an object of one type in place of another type, among the objects permitted by inheritance and implementations. For example, if we write <\/P><br \/>\n<BLOCKQUOTE><PRE>Object obj = new MountainBike();<br \/>\n<\/PRE><\/BLOCKQUOTE>then <CODE>obj<\/CODE> is both an <CODE>Object<\/CODE> and a <CODE>Mountainbike<\/CODE> (until such time as <CODE>obj<\/CODE> is assigned another object that is <I>not<\/I> a <CODE>Mountainbike<\/CODE>). This is called <I>implicit casting<\/I>.<br \/>\n<P>If, on the other hand, we write <\/P><br \/>\n<BLOCKQUOTE><PRE>MountainBike myBike = obj;<br \/>\n<\/PRE><\/BLOCKQUOTE>we would get a compile-time error because <CODE>obj<\/CODE> is not known to the compiler to be a <CODE>MountainBike<\/CODE>. However, we can <I>tell<\/I> the compiler that we promise to assign a <CODE>MountainBike<\/CODE> to <CODE>obj<\/CODE> by <I>explicit casting:<\/I><br \/>\n<BLOCKQUOTE><PRE>MountainBike myBike = (MountainBike)obj;<br \/>\n<\/PRE><\/BLOCKQUOTE>This cast inserts a runtime check that <CODE>obj<\/CODE> is assigned a <CODE>MountainBike<\/CODE> so that the compiler can safely assume that <CODE>obj<\/CODE> is a <CODE>MountainBike<\/CODE>. If <CODE>obj<\/CODE> is not a <CODE>Mountainbike<\/CODE> at runtime, an exception will be thrown.<br \/>\n<BLOCKQUOTE><br \/>\n<HR><br \/>\n<STRONG>Note:<\/STRONG>&nbsp;You can make a logical test as to the type of a particular object using the <CODE>instanceof<\/CODE> operator. This can save you from a runtime error owing to an improper cast. For example:<br \/>\n<BLOCKQUOTE><PRE>if (obj instanceof MountainBike) {<br \/>\n   MountainBike myBike = (MountainBike)obj;<br \/>\n}<br \/>\n<\/PRE><\/BLOCKQUOTE>Here the <CODE>instanceof<\/CODE> operator verifies that <CODE>obj<\/CODE> refers to a <CODE>MountainBike<\/CODE> so that we can make the cast with knowledge that there will be no runtime exception thrown.<\/BLOCKQUOTE><\/BLOCKQUOTE><br \/>\n<DIV><\/DIV><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Inheritance In the preceding lessons, you have seen inheritance mentioned several times. In the Java language, classes can be derived from other classes, thereby inheriting fields and methods from those classes. Definitions:&nbsp; A class that is derived from another class is called a subclass (also a derived class, extended class, or child class). The class &hellip; <a href=\"https:\/\/www.strongd.net\/?p=405\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">Inheritance<\/span><\/a><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[],"tags":[],"class_list":["post-405","post","type-post","status-publish","format-standard","hentry"],"_links":{"self":[{"href":"https:\/\/www.strongd.net\/index.php?rest_route=\/wp\/v2\/posts\/405","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.strongd.net\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.strongd.net\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.strongd.net\/index.php?rest_route=\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.strongd.net\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=405"}],"version-history":[{"count":0,"href":"https:\/\/www.strongd.net\/index.php?rest_route=\/wp\/v2\/posts\/405\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.strongd.net\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=405"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.strongd.net\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=405"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.strongd.net\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=405"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}