Java Inheritance

Introduction to Java Inheritance  

Java Inheritance defines an is-a relationship between a superclass and its subclasses. This means that an object of a subclass can be used wherever an object of the superclass can be used. Class Inheritance in java mechanism is used to build new classes from existing classes. The inheritance relationship is transitive: if class x extends class y, then a class z, which extends class x, will also inherit from class y.
For example a car class can inherit some properties from a General vehicle class. Here we find that the base class is the vehicle class and the subclass is the more specific car class. A subclass must use the extends clause to derive from a super class which must be written in the header of the subclass definition. The subclass inherits members of the superclass and hence promotes code reuse. The subclass itself can add its own new behavior and properties. The java.lang.Object class is always at the top of any Class inheritance hierarchy.

Java Inheritance Example - 1

class Box {

 double width;
 double height;
 double depth;
 Box() {
 }
 Box(double w, double h, double d) {
  width = w;
  height = h;
  depth = d;
 }
 void getVolume() {
  System.out.println("Volume is : " + width * height * depth);
 }
}

public class MatchBox extends Box {

 double weight;
 MatchBox() {
 }
 MatchBox(double w, double h, double d, double m) {
  super(w, h, d);
  weight = m;
 }
 public static void main(String args[]) {
  MatchBox mb1 = new MatchBox(10, 10, 10, 10);
  mb1.getVolume();
  System.out.println("width of MatchBox 1 is " + mb1.width);
  System.out.println("height of MatchBox 1 is " + mb1.height);
  System.out.println("depth of MatchBox 1 is " + mb1.depth);
  System.out.println("weight of MatchBox 1 is " + mb1.weight);
 }
}
Output
Volume is : 1000.0
width of MatchBox 1 is 10.0
height of MatchBox 1 is 10.0
depth of MatchBox 1 is 10.0
weight of MatchBox 1 is 10.0
Download MatchBox.java
What is not possible using java class Inheritance?
1. Private members of the superclass are not inherited by the subclass and can only be indirectly accessed.
2. Members that have default accessibility in the superclass are also not inherited by subclasses in other packages, as these members are only accessible by their simple names in subclasses within the same package as the superclass.
3. Since constructors and initializer blocks are not members of a class, they are not inherited by a subclass.
4. A subclass can extend only one superclass

Java Inheritance Example - 2

class Vehicle {

 // Instance fields
 int noOfTyres; // no of tyres
 private boolean accessories; // check if accessorees present or not
 protected String brand; // Brand of the car
 // Static fields
 private static int counter; // No of Vehicle objects created
 // Constructor
 Vehicle() {
  System.out.println("Constructor of the Super class called");
  noOfTyres = 5;
  accessories = true;
  brand = "X";
  counter++;
 }
 // Instance methods
 public void switchOn() {
  accessories = true;
 }
 public void switchOff() {
  accessories = false;
 }
 public boolean isPresent() {
  return accessories;
 }
 private void getBrand() {
  System.out.println("Vehicle Brand: " + brand);
 }
 // Static methods
 public static void getNoOfVehicles() {
  System.out.println("Number of Vehicles: " + counter);
 }
}

class Car extends Vehicle {

 private int carNo = 10;
 public void printCarInfo() {
  System.out.println("Car number: " + carNo);
  System.out.println("No of Tyres: " + noOfTyres); // Inherited.
  //  System.out.println("accessories: "    + accessories); 
                // Not Inherited.
  System.out.println("accessories: " + isPresent()); // Inherited.
  //        System.out.println("Brand: "     + getBrand());  
                // Not Inherited.
  System.out.println("Brand: " + brand); // Inherited.
  //  System.out.println("Counter: "    + counter);     // Not Inherited.
  getNoOfVehicles(); // Inherited.
 }
}

public class VehicleDetails { // (3)

 public static void main(String[] args) {
  new Car().printCarInfo();
 }
}
Output
Constructor of the Super class called
Car number: 10
No of Tyres: 5
accessories: true
Brand: X
Number of Vehicles: 1
Download VehicleDetails.java

THIS AND SUPER KEYWORDS

The two keywords, this and super to help you explicitly name the field or method that you want. Using this and super you have full control on whether to call a method or field present in the same class or to call from the immediate superclass. This keyword is used as a reference to the current object which is an instance of the current class. The keyword super also references the current object, but as an instance of the current class’s super class.
The this reference to the current object is useful in situations where a local variable hides, or shadows, a field with the same name. If a method needs to pass the current object to another method, it can do so using the this reference. Note that the this reference cannot be used in a static context, as static code is not executed in the context of any object.

THIS AND SUPER Example

class Counter {

 int i = 0;
 Counter increment() {
  i++;
  return this;
 }
 void print() {
  System.out.println("i = " + i);
 }
}

public class CounterDemo extends Counter {

 public static void main(String[] args) {
  Counter x = new Counter();
  x.increment().increment().increment().print();
 }
}
Output
Volume is : 1000.0
width of MatchBox 1 is 10.0
height of MatchBox 1 is 10.0
depth of MatchBox 1 is 10.0
weight of MatchBox 1 is 10.0
Download CounterDemo.java

No comments:

Post a Comment