• In the Java language, classes can be derived from other classes, thereby inheriting fields and methods from those classes.


  • Definitions: A class that is derived from another class is called a subclass (also a derived class, extended class, or child class).


  • The class from which the subclass is derived is called a superclass (also a base class or a parent class).


  • Excepting Object, which has no superclass, every class has one and only one direct superclass (single inheritance).


  • In the absence of any other explicit superclass, every class is implicitly a subclass of Object.


  • Classes can be derived from classes that are derived from classes that are derived from classes, and so on, and ultimately derived from the topmost class, Object.


  • Such a class is said to be descended from all the classes in the inheritance chain stretching back to Object.


  • The idea of inheritance is simple but powerful: When you want to create a new class and there is already a class that includes some of the code that you want, you can derive your new class from the existing class.


  • In doing this, you can reuse the fields and methods of the existing class without having to write them yourself.


  • 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 Java Platform Class Hierarchy The Object class, defined in the java.lang package, defines and implements behavior common to all classes—including the ones that you write. In the Java platform, many classes derive directly from Object, other classes derive from some of those classes, and so on, forming a hierarchy of classes.


  • All Classes in the Java Platform are Descendants of Object


  • All Classes in the Java Platform are Descendants of Object


  • At the top of the hierarchy, Object is the most general of all classes.


  • Classes near the bottom of the hierarchy provide more specialized behavior.


  • An Example of Inheritance. Here Bicycle is the parent class and MountainBike is the subclass. From the main when you can call a method of base class using object of derived class.


  •  
    class Bicycle {
            
        // the Bicycle class has three fields
        public int cadence;
       
            
        // the Bicycle class has one constructor
        public Bicycle(int startCadence) {
           
            cadence = startCadence;
           
        }
            
        // the Bicycle class has one method
        public void setCadence(int newValue) {
            cadence = newValue;
             System.out.println("Cadence"+cadence);
        }
            
    }
    
    
     class MountainBike extends Bicycle {
            
        // the MountainBike subclass adds one field
        public int seatHeight;
    
        // the MountainBike subclass has one constructor
        public MountainBike(int startHeight,
                            int startCadence) {
            super(startCadence);
            seatHeight = startHeight;
        }   
            
        // the MountainBike subclass adds one method
        public void setHeight(int newValue) {
            seatHeight = newValue;
            System.out.println("Seatheight"+seatHeight);
        }   
    }
    
    
    class Main
    {
        public static void main (String[] args)
        {
            MountainBike obj = new MountainBike(10,120);
            obj.setHeight(100);
            obj.setCadence(100);
            
        }
    }
    
    
    
    
    
    
  • MountainBike inherits all the fields and methods of Bicycle and adds the field seatHeight and a method to set it.


  • Except for the constructor, it is as if you had written a new MountainBike class entirely from scratch, with four fields and five methods.


  • However, you didn't have to do all the work. This would be especially valuable if the methods in the Bicycle class were complex and had taken substantial time to debug.


  • A subclass inherits all of the public and protected members of its parent.


  • You can use the inherited members as is, replace them, hide them, or supplement them with new members:


  • The inherited fields can be used directly, just like any other fields.


  • 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 declare new fields in the subclass that are not in the superclass.


  • The inherited methods can be used directly as they are.


  • You can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it.


  • You can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it.


  • You can declare new methods in the subclass that are not in the superclass.


  • You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super.


  • 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.


  • Casting Objects We have seen that an object is of the data type of the class from which it was instantiated. For example, if we write


  •  
    public MountainBike myBike = new MountainBike();
    
    
    
  • then myBike is of type MountainBike.


  • MountainBike is descended from Bicycle.


  • Therefore, a MountainBike is a Bicycle, and it can be used wherever Bicycleare called for.


  • The reverse is not necessarily true: a Bicycle may be a MountainBike, but it isn't necessarily.


  • Casting shows the use of an object of one type in place of another type, among the objects permitted by inheritance and implementations. For example, if we write


  •  
    Bicycle obj = new MountainBike();
    
    
    
  • then obj is both an Bicycle and a MountainBike. This is called implicit casting. When obj is created, the constructor of MountainBike class is called but obj cannot be used to execute a method of class MountainBike.


  • One significant difference between classes and interfaces is that classes can have fields whereas interfaces cannot.


  • In addition, you can instantiate a class to create an object, which you cannot do with interfaces.


  • As explained earlier an object stores its state in fields, which are defined in classes.


  • One reason why the Java programming language does not permit you to extend more than one class is to avoid the issues of multiple inheritance of state, which is the ability to inherit fields from multiple classes.


  • However, Default methods introduce one form of multiple inheritance of implementation.


  • A class can implement more than one interface, which can contain default methods that have the same name.


  • The Java compiler provides some rules to determine which default method a particular class uses.


  • The Java programming language supports multiple inheritance of type, which is the ability of a class to implement more than one interface.


  • An object can have multiple types: the type of its own class and the types of all the interfaces that the class implements.


  • This means that if a variable is declared to be the type of an interface, then its value can reference any object that is instantiated from any class that implements the interface. This is discussed in the section Using an Interface as a Type.


  • As with multiple inheritance of implementation, a class can inherit different implementations of a method defined (as default or static) in the interfaces that it extends. In this case, the compiler or the user must decide which one to use.


  • 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 that it overrides.


  • An overriding method can also return a subtype of the type returned by the overridden method. This subtype is called a covariant return type.


  • If a subclass defines a static method with the same signature as a static method in the superclass, then the method in the subclass hides the one in the superclass.


  • The distinction between hiding a static method and overriding an instance method has important implications:


  • The version of the overridden instance method that gets invoked is the one in the subclass.


  • The version of the hidden static method that gets invoked depends on whether it is invoked from the superclass or the subclass.


  • Consider an example that contains two classes.


  • The first is Animal, which contains one instance method and one static method.


  • The second class, a subclass of Animal, is called Cat:


  •  
    
    class Animal {
        public static void testClassMethod() {
            System.out.println("The static method in Animal");
        }
        public void testInstanceMethod() {
            System.out.println("The instance method in Animal");
        }
    }
    
    
    class Cat extends Animal {
        public static void testClassMethod() {
            System.out.println("The static method in Cat");
        }
        public void testInstanceMethod() {
            System.out.println("The instance method in Cat");
        }
    
        public static void main(String[] args) {
            Main myCat = new Main();
            Animal myAnimal = myCat;
            Animal.testClassMethod();
            Main.testClassMethod();
            myAnimal.testInstanceMethod();
        }
    }
    
    
    Output
    The static method in Animal                                                                        
    The static method in Cat                                                                           
    The instance method in Cat
    
    
  • The Cat class overrides the instance method in Animal and hides the static method in Animal.


  • The main method in this class creates an instance of Cat and invokes testClassMethod() on the class and testInstanceMethod() on the instance.


  • As promised, the version of the hidden static method that gets invoked is the one in the superclass, and the version of the overridden instance method that gets invoked is the one in the subclass.


  • Default methods and abstract methods in interfaces are inherited like instance methods.


  • However, when the supertypes of a class or interface provide multiple default methods with the same signature, the Java compiler follows inheritance rules to resolve the name conflict.


  • These rules are driven by the following two principles:


  • Instance methods are preferred over interface default methods.


  • Consider the following classes and interfaces:


  •  
    public class Horse {
        public String identifyMyself() {
            return "I am a horse.";
        }
    }
    public interface Flyer {
        default public String identifyMyself() {
            return "I am able to fly.";
        }
    }
    public interface Mythical {
        default public String identifyMyself() {
            return "I am a mythical creature.";
        }
    }
    public class Pegasus extends Horse implements Flyer, Mythical {
        public static void main(String[] args) {
            Pegasus myApp = new Pegasus();
            System.out.println(myApp.identifyMyself());
        }
    }
    
    
    
    
  • The method Pegasus.identifyMyself returns the string I am a horse.


  • Methods that are already overridden by other candidates are ignored. This circumstance can arise when supertypes share a common ancestor.


  • Consider the following interfaces and classes:


  •  
    public interface Animal {
        default public String identifyMyself() {
            return "I am an animal.";
        }
    }
    
    public interface EggLayer extends Animal {
        default public String identifyMyself() {
            return "I am able to lay eggs.";
        }
    }
    
    public interface FireBreather extends Animal { }
    
    
    public class Dragon implements EggLayer, FireBreather {
        public static void main (String[] args) {
            Dragon myApp = new Dragon();
            System.out.println(myApp.identifyMyself());
        }
    }
    
    
    
  • The method Dragon.identifyMyself returns the string I am able to lay eggs.


  • If two or more independently defined default methods conflict, or a default method conflicts with an abstract method, then the Java compiler produces a compiler error.


  • You must explicitly override the supertype methods.


  • Consider the example about computer-controlled cars that can now fly.


  • You have two interfaces (OperateCar and FlyCar) that provide default implementations for the same method, (startEngine):


  •  
    public interface OperateCar {
       
        default public int startEngine(EncryptedKey key) {
            // Implementation
        }
    }
    public interface FlyCar {
      
        default public int startEngine(EncryptedKey key) {
            // Implementation
        }
    }
    
    
    
  • A class that implements both OperateCar and FlyCar must override the method startEngine.


  • You could invoke any of the of the default implementations with the super keyword.


  •  
    public class FlyingCar implements OperateCar, FlyCar {
       
       
        public int startEngine(EncryptedKey key) {
            FlyCar.super.startEngine(key);
            OperateCar.super.startEngine(key);
        }
    }
    
    
    
  • The name preceding super (in this example, FlyCar or OperateCar) must refer to a direct superinterface that defines or inherits a default for the invoked method.


  • This form of method invocation is not restricted to differentiating between multiple implemented interfaces that contain default methods with the same signature.


  • You can use the super keyword to invoke a default method in both classes and interfaces.


  • Inherited instance methods from classes can override abstract interface methods.


  • Considerthe following interfaces and classes:


  •  
    public interface Mammal {
        String identifyMyself();
    }
    public class Horse {
        public String identifyMyself() {
            return "I am a horse.";
        }
    }
    public class Mustang extends Horse implements Mammal {
        public static void main(String[] args) {
            Mustang myApp = new Mustang();
            System.out.println(myApp.identifyMyself());
        }
    }
    
    
    
    
  • The method Mustang.identifyMyself returns the string I am a horse. The class Mustang inherits the method identifyMyself from the class Horse, which overrides the abstract method of the same name in the interface Mammal.


  • Note: Static methods in interfaces are never inherited.


  • Modifiers The access specifier for an overriding method can allow more, but not less, access than the overridden method. For example, a protected instance method in the superclass can be made public, but not private, in the subclass.


  • You will get a compile-time error if you attempt to change an instance method in the superclass to a static method in the subclass, and vice versa.


  • Summary The following table summarizes what happens when you define a method with the same signature as a method in a superclass.


  • Defining a Method with the Same Signature as a Superclass's Method
      Superclass Instance Method Superclass Static Method
    Subclass Instance Method Overrides Generates a compile-time error
    Subclass Static Method Generates a compile-time error Hides