0% found this document useful (0 votes)
16 views

10 - Encapsulation, Inheritance and Overrriding

Inheritance allows one class to inherit properties like methods and fields from another superclass. The subclass inherits all non-private members of the superclass. The extends keyword is used to inherit from a superclass. A subclass can access members of the superclass using super. The instanceof operator can check the inheritance relationship between classes.

Uploaded by

kevin Yego
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

10 - Encapsulation, Inheritance and Overrriding

Inheritance allows one class to inherit properties like methods and fields from another superclass. The subclass inherits all non-private members of the superclass. The extends keyword is used to inherit from a superclass. A subclass can access members of the superclass using super. The instanceof operator can check the inheritance relationship between classes.

Uploaded by

kevin Yego
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Java - Inheritance

Inheritance can be defined as the process where one class acquires the properties (methods and
fields) of another. With the use of inheritance the information is made manageable in a
hierarchical order.

The class which inherits the properties of other is known as subclass (derived class, child class)
and the class whose properties are inherited is known as superclass (base class, parent class).

extends Keyword
extends is the keyword used to inherit the properties of a class. Following is the syntax of
extends keyword.

Syntax

class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}

Sample Code
Following is an example demonstrating Java inheritance. In this example, you can observe two
classes namely Calculation and My_Calculation.

Using extends keyword, the My_Calculation inherits the methods addition() and Subtraction() of
Calculation class.

Copy and paste the following program in a file with name My_Calculation.java

Example

Live Demo
class Calculation {
int z;

public void addition(int x, int y) {


z = x + y;
System.out.println("The sum of the given numbers:"+z);
}

public void Subtraction(int x, int y) {


z = x - y;

Page 1 of 15
System.out.println("The difference between the given numbers:"+z);
}
}

public class My_Calculation extends Calculation {


public void multiplication(int x, int y) {
z = x * y;
System.out.println("The product of the given numbers:"+z);
}

public static void main(String args[]) {


int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b);
}
}

Compile and execute the above code as shown below.

javac My_Calculation.java
java My_Calculation

After executing the program, it will produce the following result −

Output

The sum of the given numbers:30


The difference between the given numbers:10
The product of the given numbers:200

In the given program, when an object to My_Calculation class is created, a copy of the contents
of the superclass is made within it. That is why, using the object of the subclass you can access
the members of a superclass.

The Superclass reference variable can hold the subclass object, but using that variable you can
access only the members of the superclass, so to access the members of both classes it is
recommended to always create reference variable to the subclass.

Page 2 of 15
If you consider the above program, you can instantiate the class as given below. But using the
superclass reference variable ( cal in this case) you cannot call the method multiplication(),
which belongs to the subclass My_Calculation.

Calculation cal = new My_Calculation();


demo.addition(a, b);
demo.Subtraction(a, b);

Note − A subclass inherits all the members (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.

The super keyword


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 superclass from the members of subclass, if


they have same names.
 It is used to invoke the superclass constructor from subclass.

Differentiating the Members

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 as shown
below.

super.variable
super.method();

Sample Code

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.

Example

Live Demo
class Super_class {
int num = 20;

Page 3 of 15
// display method of superclass
public void display() {
System.out.println("This is the display method of superclass");
}
}

public class Sub_class extends Super_class {


int num = 10;

// display method of sub class


public void display() {
System.out.println("This is the display method of subclass");
}

public void my_method() {


// Instantiating subclass
Sub_class sub = new Sub_class();

// Invoking the display() method of sub class


sub.display();

// Invoking the display() method of superclass


super.display();

// printing the value of variable num of subclass


System.out.println("value of the variable named num in sub class:"+
sub.num);

// printing the value of variable num of superclass


System.out.println("value of the variable named num in super class:"+
super.num);
}

public static void main(String args[]) {


Sub_class obj = new Sub_class();
obj.my_method();
}
}

Compile and execute the above code using the following syntax.

javac Super_Demo
java Super

On executing the program, you will get the following result −

Output

This is the display method of subclass


This is the display method of superclass
value of the variable named num in sub class:10
value of the variable named num in super class:20

Page 4 of 15
Invoking Superclass Constructor
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

Example

Live Demo
class Superclass {
int age;

Superclass(int age) {
this.age = age;
}

public void getAge() {


System.out.println("The value of the variable named age in super class
is: " +age);
}
}

public class Subclass extends Superclass {


Subclass(int age) {
super(age);
}

public static void main(String argd[]) {


Subclass s = new Subclass(24);
s.getAge();
}
}

Compile and execute the above code using the following syntax.

javac Subclass
java Subclass

On executing the program, you will get the following result −

Page 5 of 15
Output

The value of the variable named age in super class is: 24

IS-A Relationship
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

With the use of the extends keyword, the subclasses will be able to inherit all the properties of
the superclass except for the private properties of the superclass.

We can assure that Mammal is actually an Animal with the use of the instance operator.

Example

Live Demo
class Animal {
}

class Mammal extends Animal {


}

Page 6 of 15
class Reptile extends Animal {
}

public class Dog extends Mammal {

public static void main(String args[]) {


Animal a = new Animal();
Mammal m = new Mammal();
Dog d = new Dog();

System.out.println(m instanceof Animal);


System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
}

This will produce the following result −

Output

true
true
true

Since we have a good understanding of the extends keyword, let us look into how the
implements keyword is used to get the IS-A relationship.

Generally, the implements keyword is used with classes to inherit the properties of an interface.
Interfaces can never be extended by a class.

Example

public interface Animal {


}

public class Mammal implements Animal {


}

public class Dog extends Mammal {


}

The instanceof Keyword


Let us use the instanceof operator to check determine whether Mammal is actually an Animal,
and dog is actually an Animal.

Example

Live Demo
interface Animal{}
class Mammal implements Animal{}

Page 7 of 15
public class Dog extends Mammal {

public static void main(String args[]) {


Mammal m = new Mammal();
Dog d = new Dog();

System.out.println(m instanceof Animal);


System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
}

This will produce the following result −

Output

true
true
true

HAS-A relationship
These relationships are mainly based on the usage. This determines whether a certain class HAS-
A certain thing. This relationship helps to reduce duplication of code as well as bugs.

Lets look into an example −

Example

public class Vehicle{}


public class Speed{}

public class Van extends Vehicle {


private Speed sp;
}

This shows that class Van HAS-A Speed. By having a separate class for Speed, we do not have
to put the entire code that belongs to speed inside the Van class, which makes it possible to reuse
the Speed class in multiple applications.

In Object-Oriented feature, the users do not need to bother about which object is doing the real
work. To achieve this, the Van class hides the implementation details from the users of the Van
class. So, basically what happens is the users would ask the Van class to do a certain action and
the Van class will either do the work by itself or ask another class to perform the action.

Types of Inheritance
There are various types of inheritance as demonstrated below.

Page 8 of 15
A very important fact to remember is that Java does not support multiple inheritance. This means
that a class cannot extend more than one class. Therefore following is illegal −

Example

public class extends Animal, Mammal{}

However, a class can implement one or more interfaces, which has helped Java get rid of the
impossibility of multiple inheritance.

Page 9 of 15
Java - Overriding
In the previous chapter, we talked about superclasses and subclasses. If a class inherits a method
from its superclass, then there is a chance to override the method provided that it is not marked
final.

The benefit of overriding is: ability to define a behavior that's specific to the subclass type, which
means a subclass can implement a parent class method based on its requirement.

In object-oriented terms, overriding means to override the functionality of an existing method.

Example

Let us look at an example.

class Animal {
public void move() {
System.out.println("Animals can move");
}
}

class Dog extends Animal {


public void move() {
System.out.println("Dogs can walk and run");
}
}

public class TestDog {

public static void main(String args[]) {


Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object

a.move(); // runs the method in Animal class


b.move(); // runs the method in Dog class
}
}

This will produce the following result −

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.

Page 10 of 15
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.

Consider the following example −

Example
class Animal {
public void move() {
System.out.println("Animals can move");
}
}

class Dog extends Animal {


public void move() {
System.out.println("Dogs can walk and run");
}
public void bark() {
System.out.println("Dogs can bark");
}
}

public class TestDog {

public static void main(String args[]) {


Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object

a.move(); // runs the method in Animal class


b.move(); // runs the method in Dog class
b.bark();
}
}

This will produce the following result −

Output
TestDog.java:26: error: cannot find symbol
b.bark();
^
symbol: method bark()
location: variable b of type Animal
1 error

This program will throw a compile time error since b's reference type Animal doesn't have a
method by the name of bark.

Rules for Method Overriding


 The argument list should be exactly the same as that of the overridden method.

Page 11 of 15
 The return type should be the same or a subtype of the return type declared in the original
overridden method in the superclass.
 The access level cannot be more restrictive than the overridden method's access level. For
example: If the superclass method is declared public then the overridding method in the
sub class cannot be either private or protected.
 Instance methods can be overridden only if they are inherited by the subclass.
 A method declared final cannot be overridden.
 A method declared static cannot be overridden but can be re-declared.
 If a method cannot be inherited, then it cannot be overridden.
 A subclass within the same package as the instance's superclass can override any
superclass method that is not declared private or final.
 A subclass in a different package can only override the non-final methods declared public
or protected.
 An overriding method can throw any uncheck exceptions, regardless of whether the
overridden method throws exceptions or not. However, the overriding method should not
throw checked exceptions that are new or broader than the ones declared by the
overridden method. The overriding method can throw narrower or fewer exceptions than
the overridden method.
 Constructors cannot be overridden.

Using the super Keyword


When invoking a superclass version of an overridden method the super keyword is used.

Example
class Animal {
public void move() {
System.out.println("Animals can move");
}
}

class Dog extends Animal {


public void move() {
super.move(); // invokes the super class method
System.out.println("Dogs can walk and run");
}
}

public class TestDog {

public static void main(String args[]) {


Animal b = new Dog(); // Animal reference but Dog object
b.move(); // runs the method in Dog class
}
}

This will produce the following result −

Page 12 of 15
Output
Animals can move
Dogs can walk and run

Page 13 of 15
Java - Encapsulation
Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance,
polymorphism, and abstraction.

Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the
data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden
from other classes, and can be accessed only through the methods of their current class.
Therefore, it is also known as data hiding.

To achieve encapsulation in Java −

 Declare the variables of a class as private.


 Provide public setter and getter methods to modify and view the variables values.

Example

Following is an example that demonstrates how to achieve Encapsulation in Java −

/* File name : EncapTest.java */


public class EncapTest {
private String name;
private String idNum;
private int age;

public int getAge() {


return age;
}

public String getName() {


return name;
}

public String getIdNum() {


return idNum;
}

public void setAge( int newAge) {


age = newAge;
}

public void setName(String newName) {


name = newName;
}

public void setIdNum( String newId) {


idNum = newId;
}
}

Page 14 of 15
The public setXXX() and getXXX() methods are the access points of the instance variables of
the EncapTest class. Normally, these methods are referred as getters and setters. Therefore, any
class that wants to access the variables should access them through these getters and setters.

The variables of the EncapTest class can be accessed using the following program −

/* File name : RunEncap.java */


public class RunEncap {

public static void main(String args[]) {


EncapTest encap = new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");

System.out.print("Name : " + encap.getName() + " Age : " +


encap.getAge());
}
}

This will produce the following result −

Output
Name : James Age : 20

Benefits of Encapsulation
 The fields of a class can be made read-only or write-only.
 A class can have total control over what is stored in its fields.

Page 15 of 15

You might also like