Inheritance I
- Contents
- What is Inheritance?
- The “is a” Relationship
- Inheritance, Fields, and Methods
- Inheritance and Constructors
- Overriding Superclass Methods
- Preventing a Method from Being Overridden
- Protected Members
- Default Members
- Access Specifiers
- Chain of Inheritance
What is Inheritance?
Generalization vs. Specialization
Real-life objects are typically specialized versions of other more general objects.
For example, the term “insect” describes a very general type of creature with numerous characteristics.
Grasshoppers and bumblebees are insects.
They share the general characteristics of insects
They have special characteristics of their own.
- Grasshoppers have a jumping ability.
- Bumblebees have a stinger.
Grasshoppers and bumblebees are specialized versions of insects.
Another Example depicted as a diagram:
The “is a” Relationship
The relationship between a superclass and an inherited class is called an “is a” relationship.
- A grasshopper “is a” insect.
- A square “is a” rectangle.
- A square “is a” quadrilateral.
- A square “is a” shape.
A specialized object has:
- all of the characteristics of the general object
- plus additional characteristics that make it special
In object-oriented programming, inheritance is used to create an “is a” relationship among classes.
We can extend the capabilities of a class.
Inheritance involves a superclass and a subclass.
- The superclass is the general class.
- The subclass is the specialized class.
The subclass is based on, or extended from, the superclass.
- Superclasses are also called base classes.
- Subclasses are also called derived classes.
The relationship of classes can be thought of as parent classes and child classes.
The subclass inherits fields and methods from the superclass without any of them being rewritten.
New fields and methods may be added to the subclass.
The Java keyword
extends
is used on the class header to define the subclass.public class Square extends Shape
Book example:
Another Example depicted as a diagram:
Inheritance, Fields, and Methods
Members of the superclass can be marked as
private
.They are not inherited by the subclass.
They exist in memory when an object of the subclass is created.
They may be accessed only from the subclass by public methods of the superclass.
Members of the superclass can be marked as
public
.They are inherited by the subclass.
They may be directly accessed from the subclass.
When an instance of the subclass is created, the non-private methods of the superclass are available through the subclass object.
Non-private methods and fields of the superclass are available in the subclass.
Example code:
public class Program { public static void main(final String[] args) { final Square mySquare = new Square(5); System.out.println("Area Size: " + mySquare.areaSize()); System.out.println("Color: " + mySquare.getColor()); } } class Rectangle { private int length; private int width; private String color = "Red"; public Rectangle(final int length, final int width) { this.length = length; this.width = width; } public int areaSize() { return this.length * this.width; } public void setColor(final String color) { this.color = color; } public String getColor() { return this.color; } } class Square extends Rectangle { private int edge; public Square(final int edge) { super(edge, edge); } }
Inheritance and Constructors
Constructors are not inherited
When a subclass is instantiated, the superclass default constructor is executed first.
Book example:
The Superclass’s Constructor
The
super
keyword refers to an object’s superclass.The superclass constructor can be explicitly called from the subclass using the
super
keyword.Book example:
If a parameterized constructor is defined in the superclass, the superclass must provide a no-argument constructor, or
- the subclass must provide a constructor.
- the subclass must call a superclass constructor.
Calls to a superclass constructor must be the first java statement in the subclass constructors.
Example code: (for calling superclass’s constructor)
- refer to the previous example.
Example code: (for no-argument superclass constructor)
public class Program { public static void main(final String[] args) { final Rectangle myRect = new Rectangle(10, 8); System.out.println("Area Size: " + myRect.areaSize()); System.out.println(); System.out.println("Color: " + myRect.getColor()); System.out.println("Shape Name: " + myRect.getShapeName()); myRect.setColor("Red"); myRect.setShapeName("Rectangle"); System.out.println(); System.out.println("Color: " + myRect.getColor()); System.out.println("Shape Name: " + myRect.getShapeName()); } } class Shape { private String shapeName; private String color; public void setColor(final String color) { this.color = color; } public String getColor() { return this.color; } public void setShapeName(final String name) { this.shapeName = name; } public String getShapeName() { return this.shapeName; } } class Rectangle extends Shape { private final int length; private final int width; public Rectangle(final int length, final int width) { this.length = length; this.width = width; } public int areaSize() { return this.length * this.width; } }
Overriding Superclass Methods
A subclass may have a method with the same signature as a superclass method.
The subclass method overrides the superclass method.
This is known as method overriding.
Book example:
Example:
Recall that the method's signature consists of
- the method’s name
- the data type method’s parameters in the order that they appear
A subclass method that overrides a superclass method must have the same signature as the superclass method.
An object of the subclass invokes the subclass’s version of the method, not the superclass’s.
A subclass method can call the overridden superclass method via the
super
keyword.There is a distinction between overloading a method and overriding a method.
Overloading is when a method has the same name as one or more other methods, but with a different signature.
When a method overrides another method, however, they both have the same signature.
Both overloading and overriding can take place in an inheritance relationship.
Overriding can only take place in an inheritance relationship.
Book example:
Example code:
public class Program { public static void main(final String[] args) { Rectangle myShape; System.out.println("Show Rectangle:"); myShape = new Rectangle(10, 8); myShape.show(); System.out.println(); System.out.println("Show Square:"); myShape = new Square(6); myShape.show(); } } class Rectangle { private final int length; private final int width; public Rectangle(final int length, final int width) { this.length = length; this.width = width; } public void show() { System.out.println("A rectangle with length " + this.length + " and width " + this.width); } } class Square extends Rectangle { private int edge; public Square(final int edge) { super(edge, edge); } // Overriding the show method in the Rectangle class. @Override public void show() { super.show(); System.out.println("-- and is a square"); } }
Preventing a Method from Being Overridden
The
final
modifier will prevent the overriding of a superclass method in subclass.public final void show()
When the
final
is modifier applied to a class, it indicates that the class cannot be used as a base class.public final class Math
If a subclass attempts to override a
final
method, the compiler generates an error.- Cannot override the final method from XXX
This ensures that a particular superclass method is used by subclasses rather than a modified version of it.
Example code:
- refer to the previous example
- add
final
before theshow
method for theRectangle
class.
Protected Members
Java provides a third access specification:
protected
Protected members of class.
- They may be accessed by methods in a subclass.
- They may be accessed by methods in the same package as the class.
A
protected
member’s access is somewhere betweenprivate
andpublic
.Book example:
Using
protected
instead ofprivate
makes some tasks easier.Any subclass that is derived from a superclass, or is in the same package, has unrestricted access to the protected member in the superclass.
- Any method in the same package many access the
protected
members. Usually, it is better to make all fields
private
and then providepublic
methods for accessing those fields.Example code:
- refer to the example in section: Inheritance, Fields, and Methods
- add keyword
protected
before thecolor
field in theRectangle
class.
Default Members
If no access specifier for a class member is provided, the class member is given package access by default.
Access Specifiers
Access Modifier | Accessible to a subclass in side the same package? | Accessible to all other classes inside the same package? | Accessible to a subclass outside the package? | Accesible to all other classes outside the package? |
public | Yes | Yes | Yes | Yes |
protected | Yes | Yes | Yes | No |
default (no modifier) | Yes | Yes | No | No |
private | No | No | No | No |
Chain of Inheritance
A superclass can also be derived from another class.
Book example:
Classes often are depicted graphically in a class hierarchy.
A class hierarchy shows the inheritance relationships between classes.
Example:
Another Example contains abstract classes, which we will discuss soon.
Example code:
public class Program { public static void main(final String[] args) { Shape myShape; myShape = new Rectangle(8, 10, "Red"); myShape.show(); myShape = new Square(9, "Blue"); myShape.show(); } } class Shape { private String shapeName; private String color; public Shape(final String shapeName, final String color) { this.shapeName = shapeName; this.color = color; } public String getColor() { return this.color; } public void show() { System.out.println("A shape named: " + this.shapeName + " with color " + this.color); } } class Rectangle extends Shape { private int length; private int width; public Rectangle(final int length, final int width, final String color) { super("Rectangle", color); this.length = length; this.width = width; } public void show() { System.out.println("A rectangle with length " + this.length + " and width " + this.width + " and color " + this.getColor()); } } class Square extends Rectangle { private int edge; public Square(final int edge, final String color) { super(edge, edge, color); } public void show() { System.out.println("A square with edge length " + this.edge + " and color " + this.getColor()); } }