This document discusses inheritance in Java, including key concepts like superclasses and subclasses, protected members, overriding methods, using this() and super(), and using final with inheritance. It provides code examples to demonstrate these inheritance concepts and defines inheritance as allowing hierarchical classifications by deriving new classes from existing classes, thereby reusing fields and methods without rewriting code.
2. 13-04-2021 INHERITANCE 2
Outline of this chapter
1.Concept of inheritance
2.Super classes and subclasses
3.Protected members
4.Overriding methods
5.Using this () and super ()
6.Use of final with inheritance
7.Constructors in subclasses
3. 13-04-2021 INHERITANCE 3
What is Inheritance ?
Inheritance is one of the cornerstones of object-oriented programming
because it allows the creation of hierarchical classifications.
In Java, classes can be derived from classes.
Basically, if you need to create a new class and here is already a class
that has some of the code you require, then it is possible to derive your
new class from the already existing code.
This concept allows you to reuse the fields and methods of the existing
class without having to rewrite the code in a new class. In this scenario,
the existing class is called the superclass and the derived class is called
the subclass.
To inherit a class, you simply incorporate the definition of one class into
another by using the extends keyword.
4. 13-04-2021 INHERITANCE 4
Inheritance is one such concept where the properties of one class
can be inherited by the other.
It helps to reuse the code and establish a relationship between
different classes.
extends Keyword
extends is the keyword used to inherit the properties of a class.
Following is the syntax of extends keyword.
class Super{
.....
..... }
class Sub extends Super {
..... .....
}
7. 13-04-2021 INHERITANCE 7
Inheritance relationships form tree-like hierarchical structures.
A superclass exists in a hierarchical relationship with its
subclasses.
When classes participate in inheritance relationships, they
become “affiliated” with other classes.
A class becomes either a superclass, supplying members to
other classes, or a subclass, inheriting its members from other
classes
note that super classes tend to be “more general” and
subclasses “more specific.”
Super classes and Subclasses
8. 13-04-2021 INHERITANCE 8
Super class
(base/parent/driver/inheritance/ ancestor class).
Intermediate class
(mediating/dual class).
Child class
(sub/associate/derived/inherited class).
9. 13-04-2021 INHERITANCE 9
A superclass’s public members are accessible anywhere the
program has a reference to that superclass type or one of its
subclass types.
A superclass’s private members are accessible only in methods
of that superclass.
A superclass’s protected members may be accessed only by
methods of the superclass, by methods of subclasses and by
methods of other classes in the same package (protected
members have package access).
Subclass methods can normally refer to public and protected
members of the superclass simply by using the member names.
Member Access and Inheritance
10. 13-04-2021 INHERITANCE 10
class Access {
public static void main ( String
args[ ] ) {
B subob = new B ( );
subob.setij (10, 12 );
subob.sum( );
System.out.println ( “ Total is “ +
subob.total );
}}
class A {
int i; // public by default
private int j; // private to A
void setij ( int x, int y) {
i = x;
j = y;
}}
// A’s j is not accessible here
class B extends A {
int total ;
void sum ( ) {
total =i + j ; // Error, j is not accessible here
}}
/ * In a class hierarchy, private members remain private to their class.
This program contains an error and will not compile */
11. 13-04-2021 INHERITANCE 11
The super keyword is similar to this keyword.
Following are the scenarios where the super keyword is used.
It is used to differentiate the members of super class from
the members of sub class, if they have same names.
It is used to invoke the super class constructor from subclass.
If a class is inheriting the properties of another class. And if
the members of the superclass have the names same as the sub
class, to differentiate these variables we use super keyword.
The super keyword
15. 13-04-2021 INHERITANCE 15
A subclass can call a constructor method defined by its
superclass by use of the following form of super.
super ( parameter-list );
Here, parameter-list specifies any parameters needed by the
constructor in the superclass.
super ( ) must always be the first statement executer inside a
subclass constructor.
Using super to call superclass Constructor
17. 13-04-2021 INHERITANCE 17
The first thing a subclass constructor must do is call the
superclass constructor
This ensures that the superclass part of the object is
constructed before the subclass part
If you do not call the superclass constructor with the super
keyword, and the superclass has a constructor with no
arguments, then that superclass constructor will be called
implicitly.
Subclass Constructor
18. Implicit Super Constructor Call
If I have this Food class:
public class Food {
private boolean raw;
public Food() {
raw = true;
}
}
then this Beef subclass:
public class Beef extends Food {
private double weight;
public Beef(double w) {
weight = w
}}
is equivalent to:
public class Beef extends Food {
private double weight;
public Beef(double w) {
super();
weight = w
}
}
19. 13-04-2021 INHERITANCE 19
The this keyword
A special reference value called this is included in Java .
The this keyword is used inside any instance method to refer to
the current object .
The value this refers to the object which the current method
has been called on .
The this keyword can be used where a reference to an object of
the current class type is required .
20. 13-04-2021 INHERITANCE 20
The following example illustrates the usage of the keyword this.
The output appear as given below :
22. 13-04-2021 INHERITANCE 22
In a class hierarchy, when a method in a subclass has the same and
type signature as a method in its superclass, then the method in the
subclass is said to override the method in the superclass.
When an overridden method is called from within a subclass, it will
always refer to the version of that method defined by the subclass.
The version of the method defined by the superclass will be hidden.
In object-oriented terms, overriding means to override the
functionality of an existing method.
If subclass (child class) has the same method as declared in the
parent class, it is known as method overriding in Java.
Method Overriding
24. 13-04-2021 INHERITANCE 24
Usage of Java Method Overriding
Method overriding is used to provide the specific
implementation of a method which is already provided by its
superclass.
Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
The method must have the same name as in the parent class
The method must have the same parameter as in the parent
class.
There must be an IS-A relationship (inheritance).
26. 13-04-2021 INHERITANCE 26
final is a keyword in java used for restricting some
functionalities. We can declare variables, methods and classes
with final keyword.
The keyword final has three uses.
1. Using final to create the equivalent of a named constant.
2. Using final to Prevent Overriding
3. Using final to prevent Inheritance
Using final with Inheritance
27. 13-04-2021 INHERITANCE 27
final class A
{
// methods and fields
}
// The following class is illegal.
class B extends A {
// ERROR! Can't subclass A
}
Using final to Prevent Inheritance
28. 13-04-2021 INHERITANCE 28
Using final to Prevent Overriding
When a method is declared as final then it cannot be overridden by
subclasses.
class A {
final void m1()
{
System.out.println("This is a final method.");
} }
class B extends A {
void m1()
{ // ERROR! Can't override.
System.out.println("Illegal!");
} }
31. 13-04-2021 INHERITANCE 31
Note: Multiple inheritance is not supported in Java through class.
When one class inherits multiple classes, it is known as
multiple inheritance.
For Example:
Inheritance is one of the cornerstones of object-oriented programming because it allows the creation of hierarchical classifications. Using inheritance, you can create a general class that defines traits common to a set of related items. This class can then be inherited by other, more specific classes, each adding those things that are unique to it. In the terminology of Java, a class that is inherited is called a superclass. The class that does the inheriting is called a subclass. Therefore, a subclass is a specialized version of a superclass and adds its own, unique elements.
In Java, classes can be derived from classes. Basically, if you need to create a new class and here is already a class that has some of the code you require, then it is possible to derive your new class from the already existing code.
This concept allows you to reuse the fields and methods of the existing class without having to rewrite the code in a new class. In this scenario, the existing class is called the superclass and the derived class is called the subclass.
Often, an object of one class is an object of another class as well. For example, in geometry, a rectangle is a quadrilateral (as are squares, parallelograms and trapezoids). Thus, in Java, class Rectangle can be said to inherit from class Quadrilateral. In this context, class Quadrilateral is a superclass and class Rectangle is a subclass. A rectangle is a specific type of quadrilateral, but it is incorrect to claim that every quadrilateral is a rectangle—the quadrilateral could be a parallelogram or some other shape. Figure 9.1 lists several simple examples of superclasses and subclasses—note that superclasses tend to be “more general” and subclasses “more specific.”
Because every subclass object is an object of its superclass, and one superclass can have many subclasses, the set of objects represented by a superclass is typically larger than the set of objects represented by any of its subclasses. For example, the superclass Vehicle rep- resents all vehicles, including cars, trucks, boats, bicycles and so on. By contrast, subclass Car represents a smaller, more specific subset of vehicles.
Inheritance relationships form tree-like hierarchical structures. A superclass exists in a hierarchical relationship with its subclasses. When classes participate in inheritance rela- tionships, they become “affiliated” with other classes. A class becomes either a superclass, supplying members to other classes, or a subclass, inheriting its members from other classes. In some cases, a class is both a superclass and a subclass.
Although a subclass includes all of the members of its superclass, it cannot access those members of the superclass that have been declared as private .
A superclass’s public members are accessible anywhere the program has a reference to that superclass type or one of its subclass types. A superclass’s private members are accessible only in methods of that superclass.
A superclass’s protected access members serve as an intermediate level of protection between public and private access. A superclass’s protected members may be accessed only by methods of the superclass, by methods of subclasses and by methods of other classes in the same package (protected members have package access).
Subclass methods can normally refer to public and protected members of the superclass simply by using the member names. When a subclass method overrides a superclass method, the superclass method may be accessed from the subclass by preceding the superclass method name with keyword super followed by the dot operator (.). This technique is illustrated latter.
super has two general forms. The first calls the superclass constructor . The second is used to access a member of the superclass that has been hidden by a member of a
subclass.
This section provides you a program that demonstrates the usage of the super keyword.
In the given program, you have two classes namely Sub_class and Super_class, both have a method named display() with different implementations, and a variable named num with different values. We are invoking display() method of both classes and printing the value of the variable num of both classes. Here you can observe that we have used super keyword to differentiate the members of superclass from subclass.
Copy and paste the program in a file with name Sub_class.java.
This section provides you a program that demonstrates the usage of the super keyword.
In the given program, you have two classes namely Sub_class and Super_class, both have a method named display() with different implementations, and a variable named num with different values. We are invoking display() method of both classes and printing the value of the variable num of both classes. Here you can observe that we have used super keyword to differentiate the members of superclass from subclass.
Copy and paste the program in a file with name Sub_class.java.
If a class is inheriting the properties of another class, the subclass automatically acquires the default constructor of the superclass. But if you want to call a parameterized constructor of the superclass, you need to use the super keyword as shown below.
super(values); Sample Code
The program given in this section demonstrates how to use the super keyword to invoke the parametrized constructor of the superclass. This program contains a superclass and a subclass, where the superclass contains a parameterized constructor which accepts a integer value, and we used the super keyword to invoke the parameterized constructor of the superclass.
Copy and paste the following program in a file with the name Subclass.java
Using the this Keyword
Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.
Using this with a Field
The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.
For example, the Point class was written like this
public class Point { public int x = 0; public int y = 0; //constructor public Point(int a, int b) { x = a; y = b; } }
but it could have been written like this:
public class Point { public int x = 0; public int y = 0; //constructor public Point(int x, int y) { this.x = x; this.y = y; } }
Each argument to the constructor shadows one of the object's fields — inside the constructor x is a local copy of the constructor's first argument. To refer to the Point field x, the constructor must use this.x.
Using this with a Constructor
From within a constructor, you can also use the this keyword to call another constructor in the same class. Doing so is called an explicit constructor invocation. Here's another Rectangle class, with a different implementation from the one in the Objects section.
public class Rectangle {
private int x, y;
private int width, height;
public Rectangle() {
this(0, 0, 1, 1);
}
public Rectangle(int width, int height)
{
this(0, 0, width, height);
}
public Rectangle(int x, int y, int width, int height)
{
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
}
This class contains a set of constructors. Each constructor initializes some or all of the rectangle's member variables. The constructors provide a default value for any member variable whose initial value is not provided by an argument. For example, the no-argument constructor creates a 1x1 Rectangle at coordinates 0,0. The two-argument constructor calls the four-argument constructor, passing in the width and height but always using the 0,0 coordinates. As before, the compiler determines which constructor to call, based on the number and the type of arguments.
Output
Animals can move
Dogs can walk and run
In the above example, you can see that even though b is a type of Animal it runs the move method in the Dog class. The reason for this is: In compile time, the check is made on the reference type. However, in the runtime, JVM figures out the object type and would run the method that belongs to that particular object.
Therefore, in the above example, the program will compile properly since Animal class has the method move. Then, at the runtime, it runs the method specific for that object.
Using final to Prevent Inheritance
When a class is declared as final then it cannot be subclassed i.e. no any other class can extend it. This is particularly useful, for example, when creating an immutable class like the predefined String class. The following fragment illustrates final keyword with a class:
Declaring a class as final implicitly declares all of its methods as final, too.
It is illegal to declare a class as both abstract and final since an abstract class is incomplete by itself and relies upon its subclasses to provide complete implementations. For more on abstract classes, refer abstract classes in java
Using final to Prevent Overriding
When a method is declared as final then it cannot be overridden by subclasses.The Object class does this—a number of its methods are final. The following fragment illustrates final keyword with a method:
Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the same method and you call it from child class object, there will be ambiguity to call the method of A or B class.
Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error.
IS-A is a way of saying: This object is a type of that object. Let us see how the extends keyword is used to achieve inheritance.
public class Animal { } public class Mammal extends Animal { } public class Reptile extends Animal { } public class Dog extends Mammal { }Now, based on the above example, in Object-Oriented terms, the following are true −
Animal is the superclass of Mammal class.
Animal is the superclass of Reptile class.
Mammal and Reptile are subclasses of Animal class.
Dog is the subclass of both Mammal and Animal classes.
Now, if we consider the IS-A relationship, we can say −
Mammal IS-A Animal
Reptile IS-A Animal
Dog IS-A Mammal
Hence: Dog IS-A Animal as well