Tutorial 9
Tutorial 9
Inheritance
Inheritence in Java allows you to reuse code from an existing class into another class, you can derive your new
class from an existing class. Your new class is called derived class which inherits all the members from its
superclass.
The inherited fields can be used directly, just like any other fields. You can declare a field in the subclass with the
same name as the one in the superclass, thus hiding it (not recommended). You can declare new fields in the
subclass that are not in the superclass. The inherited methods can be used directly as they are. You can write a
new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it.
You can write a new static method in the subclass that has the same signature as the one in the superclass, thus
hiding it. You can declare new methods in the subclass that are not in the superclass. You can write a subclass
constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super. A
subclass does not inherit the private members of its parent class.
An example of inheritence
Consider a class called Shape, Shape is the base class which is inherited by shapes like rectangle, square, circle
etc.
Execute Code
class Circle extends Shape { // The "extends" keyword is what we use to tell java tha
t Circle inherits the functionality of Shape.
Execute Code
(http://www.dmca.com/Protection/Status.aspx?ID=fd56e7e29e1f43ccbe7ce1023cb5781c)
The advantage of using inheritance is that you can write code that can apply to a number of classes that
extendCopyright © LearnJavaOnline.org. Read our Terms of Use (/tos) and Privacy Policy (/privacy) a more
general class. In the below example we have a method that takes the larger area from the two shapes:
Execute Code
getLargerShape() doesn't require the programmer to input a specific type of shape for its 2 parameters. You could
use an instance of any class that inherits the type Shape as any of the two parameters for this method. You could
use an instance of type Circle , Rectangle , Triangle , Trapezoid , etc. as long as they extend Shape .
Exercise
Create a rectangle class which inherits the Shape class and finds the area
Start Exercise
(http://www.spoj.com/?utm_campaign=permanent&utm_medium=banner&utm_source=learnx)
(http://www.dmca.com/Protection/Status.aspx?ID=fd56e7e29e1f43ccbe7ce1023cb5781c)
Copyright © LearnJavaOnline.org. Read our Terms of Use (/tos) and Privacy Policy (/privacy)