Inheritance In Java

Inheritance In Java :

Inheritance

  • Inheritance means which one object acquires all the properties and behaviors of a parent object.
  • Derived class acquires the properties of a base class.
  • Hierarchical classification.
  • Class that is inherited or extends is called super class or base class. The class that does the inheriting is called sub class or derived class.
  • A subclass inheritance variable and methods from its super class and also has its own variables and methods.
  • final class cannot be inherited.
  • If the base class private data members then that types of members will not be inherited into derived class and private method of the base class not inherited.
  • Constructor of one class never inherited to another class.
  • Java does not support multiple inheritance.
  • For each and every class in java their exists an implicit predefined super class known as java.lang.object.

Relationship :

  • Reusing data members form one class to another class.
  • There are 3 types of relationship:

  1. Is – a relationship is one in which data members of one class is obtained into another class.
  2. Has – a relationship object of one class is create as data member in another class.
  3. Use – a relationshipmethod of one class using object of another class.

Points :

  • Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created.
  • Sub Class/Child Class: Subclass is a class which inherits the other class called a derived class, extended class, or child class.
  • Super Class/Parent Class: Superclass is the class from where a subclass inherits called a base class or a parent class.

Subclass :

  • Sub class inherits all of the public and protected members of its parent.  If the subclass is in the same package as its parent, it also inherits the package-private members of the parent.
  • 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 write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it.
  • static method in the subclass that has the same signature as the one in the superclass, thus hiding it.
  • Subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super.
  • The members of base class in a derived class so that they are accessible in that derived class that called class inheritance.
  • Derived class object always contains a base class object within it, including all the fields and method that are not inherited. For example, private variable and method cannot inherited. final class cannot be inherited. Constructor of one class never inherited to another class.
  • extends keyword of super class are inherited in sub subclass.
  • One derived class can extend only one base class.
  • Members that have accessibility in the super class are also not inherited by subclass in other packages, as these members are only accessible by their simple name in subclasses within the same package as the super class.

Private members in a Superclass :

  • A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass.
  • A nested class has access to all the private members of its enclosing class—both fields and methods. Therefore, a public or protected nested class inherited by a subclass has indirect access to all of the private members of the superclass.
  • Inheritance
    2 types of inheritance.
  1. Based on class
    • Single inheritance
    • Multilevel inheritance
    • Hierarchical inheritance
  2. Based on interface
    • Multiple inheritance
    • Hybrid inheritance
Inheritance In Java
  • Single inheritance (Only one super class)

Subclass can only one super class.

OR

One class is extended by only one class.

OR

  • When a derived class inherit the property and behavior from a single parent class.
  • The above diagram shows that class B extends only one class which is A. Here A is parent class of B and B would be child class of A.
  • In simple inheritance there is one base class (parents class, super class) and one derived class(sub class, child class).
  • Child class inherits the properties and method of parents class means child class can use the variable and methods of parents class .We can create the object of child class because the parents class inherited by child class by using “extends “keyword.
class A 
{
	int x;
	int y;
	int get(int p, int q)
	{
		x=p; 
		y=q; 
		return(0);
	}
	void Show()
	{
		System.out.println(x);
	}
}

class B extends A
{
	public static void main(String args[])
	{
		A a = new A();
		a.get(5,6);
		a.Show();
	}
	void display()
	{
		System.out.println("B");
	}
}

class animalcount
{
    private intnooflegs;

    public void setlegs(int c)
    {
nooflegs = c;
    }

    public intgetlegs()
    {
        return nooflegs;
    }
}

class animalname extends animalcount
{
    private String animalname;

    public void setname(String n)
    {
animalname = n;
    }

    public String getname()
    {
        return animalname;
    }
}

class First
{
    public static void main(String args[])
    {
animalnameobj = new animalname();
obj.setlegs(4);
obj.setname("Dog");
System.out.println("Legs Count ::" + obj.getlegs() + "\t Animal Name ::" + obj.getname());
    }
}

Multiple inheritance :

  • This form of inheritance can have server super classes. Java not support multiple inheritance, in which one class inherits from more than one class.
  • Multiple inheritance, one class extends multiple classes.
  • Java does not support multiple inheritance but the multiple inheritance can be achieved by using the interface.
  • Multiple Inheritance can be achieved through use of Interfaces by implementing more than one interfaces in a class.

class A 
{
	int x;
	int y;
	int get(int p, int q)
	{
		x=p; 
		y=q; 
		return(0);
	}
	void Show()
	{
		System.out.println(x);
	}
}

class B extends A
{
	public static void main(String args[])
	{
		A a = new A();
		a.get(5,6);
		a.Show();
	}
	void display()
	{
		System.out.println("B");
	}
}

class animalcount
{
    private intnooflegs;

    public void setlegs(int c)
    {
nooflegs = c;
    }

    public intgetlegs()
    {
        return nooflegs;
    }
}

class animalname extends animalcount
{
    private String animalname;

    public void setname(String n)
    {
animalname = n;
    }

    public String getname()
    {
        return animalname;
    }
}

class First
{
    public static void main(String args[])
    {
animalnameobj = new animalname();
obj.setlegs(4);
obj.setname("Dog");
System.out.println("Legs Count ::" + obj.getlegs() + "\t Animal Name ::" + obj.getname());
    }
}

Multilevel inheritance :

Subclass derived from another subclass.

OR

One class is extended by a class and that class in turn is extended by another class thus forming a chain of inheritance

For example: grandfather, father and child.

  • Multilevel inheritance refers to a mechanism in OO technology where one can inherit from a derived class, thereby making this derived class the base class for the new class. As you can see diagram C is subclass or child class of B and B is a child class of A.
  • The derived class is called the subclass or child class for it’s parent class and this parent class works as the child class for it’s just above (parent) class.  Multilevel inheritance can go up to any number of level.

Inheritance In Java

class A
{
int x;
int y;

int get(int p, int q)
    {
        x = p;
        y = q;
        return (0);
    }

    void Show()
    {
System.out.println(x);
    }
}

class B extends A
{
    void Showb()
    {
System.out.println("B");
    }
}

class C extends B
{
    void display()
    {
System.out.println("C");
    }

    public static void main(String args[])
    {
        A a = new A();
a.get(5, 6);
a.Show();
    }
}

class Car
{
    public Car()
    {
System.out.println("Class Car");
    }

    public void vehicleType()
    {
System.out.println("Vehicle Type: Car");
    }
}

class Maruti extends Car
{
    public Maruti()
    {
System.out.println("Class Maruti");
    }

    public void brand()
    {
System.out.println("Brand: Maruti");
    }

    public void speed()
    {
System.out.println("Max: 90Kmph");
    }
}

public class First extends Maruti
{
    public First()
    {
System.out.println("Maruti Model: 800");
    }

    public void speed()
    {
System.out.println("Max: 80Kmph");
    }

    public static void main(String args[])
    {
        First obj = new First();
obj.vehicleType();
obj.brand();
obj.speed();
    }
}

class A
{
    void add()
    {
int a, b, c;
        a = 2;
        b = 4;
System.out.println("Value C :" + a + b);
    }
}

class B extends A
{
    void mul()
    {
int a, b, c;
        a = 2;
        b = 4;
System.out.println("Value C :" + a * b);
    }
}

class C extends B
{
    void div()
    {
int a, b, c;
        a = 4;
        b = 2;
System.out.println("Value C :" + a / b);
    }
}

class Multilevel
{
    public static void main(String[] args)
    {
        C ob = new C();
ob.add();
ob.mul();
ob.div();
    }
}

Hierarchical inheritance :

This form has one super class and many subclass. More than one class inherits the traits of one class.

OR

Hierarchical type of inheritance, one class is extended by many subclasses. It is one-to-many relationship.

For example: Bank accounts.

  • Inheritance one class is inherited by many sub classes. Class B, C and D inherits the same class A. A is parent class of B, C and D.
  • When a derived class inherits it’s the properties and behavior from a derived class. It is known as multilevel inheritance.
  • When two or more derived class inherits the properties and behavior from same parent class called hierarchical inheritance.

class A
{
    public void methodA()
    {
System.out.println("method of Class A");
    }
}

class B extends A
{
    public void methodB()
    {
System.out.println("method of Class B");
    }
}

class C extends A
{
    public void methodC()
    {
System.out.println("method of Class C");
    }
}

class D extends A
{
    public void methodD()
    {
System.out.println("method of Class D");
    }
}

class MyClass
{
    public void methodB()
    {
System.out.println("method of Class B");
    }

    public static void main(String args[])
    {
        B obj1 = new B();
        C obj2 = new C();
        D obj3 = new D();
        obj1.methodA();
        obj2.methodA();
        obj3.methodA();
    }
}







class A
{
    void add()
    {
int a, b, c;
        a = 2;
        b = 4;
System.out.println("Value C :" + a + b);
    }
}

class B extends A
{
    void mul()
    {
int a, b, c;
        a = 2;
        b = 4;
System.out.println("Value C :" + a * b);
    }
}

class C extends A
{
    void div()
    {
int a, b, c;
        a = 4;
        b = 2;
System.out.println("Value C :" + a / b);
    }
}

class hierarchical
{
    public static void main(String[] args)
    {
        B ob1 = new B();
        ob1.add();
        ob1.mul();
        C ob2 = new C();
        ob2.div();
    }
}

Member Access and Inheritance :

A subclass includes all the members of its super class but it cannot access those members of the super class that have been declared as private.

class A
{
inti;
    private int j;

    void setij(int x, int y)
    {
i = x;
        j = y;
    }
}
class B extends A
{
int total;
    void sum()
    {
        total = i + j; //error j is not accessible
    }
}
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 Box
{
    double width;
    double height;
    double depth;
    Box(Box ob)
    {
        width = ob.width;
        height = ob.width;
        depth = ob.depth;
    }

    Box(double w, double h, double d)
    {
        width = w;
        height = h;
        depth = d;
    }
    Box()
    {
        width = -1;
        height = -1;
        depth = -1;
    }
    Box(double len)
    {
        width = height = depth = len;
    }
    Double volume()
    {
        return width * height * depth;
    }
}

class BoxWeight extends Box
{
    double weight;
BoxWeight(double w, double h, double d, double m)
    {
        width = w;
        height = h;
        depth = d;
        weight = m;
    }
}

class DemoBoxWeight
{
    public static void main(String args[])
    {
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.5);
BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);

        double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is:" + vol);
System.out.println("Weight of mybox1 is:" + mybox1.weight);
System.out.println();
vol = mybox2.volume();
System.out.println("Volume of mybox2 is:" + vol);
System.out.println("Weight of mybox2 is:" + mybox2.weight);
System.out.println();
    }
}

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);
	}
}
  • Hybrid Inheritance
Inheritance In Java
  • If there is class A and it is extending by class B and class C. Further, if class D inherits both class B and class C, then this type of inheritance is known as Hybrid Inheritance. It will also cause an error as class D inherits multiple classes, i.e. class B and class C.
  • As you can see in the above diagram that it’s a combine form of single and multiple inheritance. Since java doesn’t support multiple inheritance, the hybrid inheritance is also not possible.

Case 1: 

  • Using classes: If in above figure B and C are classes then this inheritance is not allowed as a single class cannot extend more than one class (Class D is extending both B and C). Reason explained below!!

Case 2:

  • Using Interfaces: If B and C are interfaces then the above hybrid inheritance is allowed as a single class can implement any number of interfaces in java.

What is diamond problem of multiple inheritance ?

  • Consider the below diagram which shows multiple inheritance as Class D extends both Class B & C.
  • Now let’s assume we have a method in class A and class B & C overrides that method in their own way.

Wait!! here the problem comes  :

  • Because D is extending both B & C so if D wants to use the same method which method would be called (the overridden method of B or the overridden method of C). Ambiguity. That’s the main reason why Java doesn’t support multiple inheritance.

Hierarchical inheritance and Hybrid inheritance are different ?

  • Yes, Hierarchical inheritance is different than hybrid inheritance.
  • Hierarchical inheritance is possible to have in java even using the classes alone itself as in this type of inheritance two or more classes have the same parent class or in other words a single parent class has two or more child classes, which is quite possible to have in java.

Disadvantages of Inheritance :

  • Both classes (super and subclasses) are tightly-coupled.
  • As they are tightly coupled (binded each other strongly with extends keyword), they cannot work independently of each other.
  • Changing the code in super class method also affects the subclass functionality.
  • If super class method is deleted, the code may not work as subclass may call the super class method with super keyword. Now subclass method behaves independently.

What is not possible using java class Inheritance ?

  • Private members of the super class are not inherited by the subclass and can only be indirectly accessed.
  • Members that have default accessibility in the super class 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 super class.
  • Since constructors and initialize blocks are not members of a class, they are not inherited by a subclass.
  • A subclass can extend only one super class.

// 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 booleanisPresent() 
{
	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 intcarNo  = 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
{ 
    public static void main(String[] args)
    {
        new Car().printCarInfo();
    }
}

Instance Methods :

  • An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass’s method.
  • The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is “close enough” and then to modify behavior as needed. The overriding method has the same name, number and type of parameters, and return type as the method it overrides. An overriding method can also return a subtype of the type returned by the overridden method. This is called a covariant return type.
  • When overriding a method, you might want to use the @Override annotation that instructs the compiler that you intend to override a method in the super class. If, for some reason, the compiler detects that the method does not exist in one of the super classes, it will generate an error. For more information on @Override, see Annotations.

Class Methods :

  • If a subclass defines a class method with the same signature as a class method in the super class, the method in the subclass hides the one in the super class.
  • The distinction between hiding and overriding has important implications. The version of the overridden method that gets invoked is the one in the subclass. The version of the hidden method that gets invoked depends on whether it is invoked from the super class or the subclass. Let’s look at an example that contains two classes. The first is Animal, which contains one instance method and one class method:

Method Binding :

  • Objects are used to call methods.
  • Method Binding us an object that can be used to call an arbitrary public method, on an instance that is acquired by evaluating the leading portion of a method binding expression via a value binding.
  • It is legal for a class to have two or more methods with the same name.
  • Java has to be able to uniquely associate the invocation of a method with its definition relying on the number and types of arguments.
  • Therefore the same – named methods must be distinguished:
  • By the number of arguments,
  • By the types of arguments
  • Overloading and inheritance are two way implement polymorphism.

The flutter tutorial  is a website that bring you the latest and amazing resources of code. All the languages codes are included in this website. The languages like flutter, android, java,kotlin etc.with the help of this languages any user can develop the beautiful application

For more information about Flutter. visit www.fluttertutorial.in