Inheritance In Java | Basic Concepts About Inheritance in Java you Need To Know !! | ISC Computer Science | ICSE Computer Applications
Inheritance
Introduction
- Inheritance means one object acquires all the properties and behaviors of the parent objects.
- Inheritance is a compile-time mechanism.
- A super-class can have any number of subclasses. But a subclass can have only one superclass.
- The extends keyword indicates that you are making a new class that derives from an existing class.
- The superclass and subclass have the “is-a” relationship between them.
- Inheritance is used For Method Overriding and For Code Reusability.
Types of Inheritance
There are 5 types of Inheritance.
- Single Inheritance: One class is extended by only one class.
- Multilevel Inheritance: One class is extended by a class and that class in turn is extended by another class thus forming a chain of inheritance.
- Hierarchical Inheritance: One class is extended by many classes.
- Hybrid Inheritance: It is a combination of the above types of inheritance.
- Multiple Inheritance: One class extends more than one class. (Java does not support multiple inheritances.)
Java does not support Multiple Inheritance
Java does not support multiple inheritances. This feature is avoided intentionally to avoid ambiguity, complexity, and confusion.
For example, If Class C extends Class A and Class B which have a method with the same name, then Class C will have two methods with the same name.
This causes ambiguity and confusion for which method to use. To avoid this, java does not supports multiple inheritances.
Method Overriding
An instance method in a subclass with the same signature (name, number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method.
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.
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 superclass.
If, for some reason, the compiler detects that the method does not exist in one of the superclasses, then it will generate an error.
Method Hiding
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.
Summary so far
The following table summarizes what happens when you define a method with the same signature as a method in a superclass.
Superclass Instance Method | Superclass Static Method | |
---|---|---|
Subclass Instance Method | Overrides | Generates a compile-time error |
Subclass Static Method | Generates a compile-time error | Hides |
Note: In a subclass, you can overload the methods inherited from the superclass.
Such overloaded methods neither hide nor override the superclass instance methods—they are new methods, unique to the subclass.
Protected Class Member
Private Class Member
Constructors and Initializers
Constructors and initializers(Static initializers and instance initializers) are not inherited to subclasses.
But, they are executed while instantiating a subclass.
Static Member
Super Keyword In Java
The super keyword in java is a reference variable that is used to refer immediate parent class object.
Whenever you create the instance of a subclass, an instance of the parent class is created implicitly i.e. referred by super reference variable.
The super keyword has three purposes
- super is used to refer immediate parent class instance variable.
- super() is used to invoke immediate parent class constructor.
- super is used to invoke the immediate parent class method.
Constructors
Most important points about constructors are
- Constructors are not inherited.
- If you do not make a constructor, the default empty constructor is automatically created.
- If any constructor does not explicitly call a super or this constructor as its first statement, a call to super() is automatically added.
In Java, the constructor of the base class with no argument gets automatically called in the derived class constructor.
But, if we want to call the parameterized constructor of the base class, then we can call it using super().
The point to note is base class constructor call must be the first line in the derived class constructor.
Method Overloading
Overloading is a process of declaring two methods with the same name but different method signature
E.g. System.out which is an object of PrintStream class has several println() method to print different data types e.g. byte, short, int, char, float, and double.
All of them are called overloaded methods. Overloaded method calls are resolved during compile time in Java and they must have different method signatures.
Rules of Overloading a Method
The only rule of method overloading is that the method signature of all overloaded methods must be different.
The method signature is changed by changing either number of method arguments, or type of method arguments e.g. System.out.println() method is overloaded to accept different primitive types like int, short, byte, float, etc.
They all accept just one argument but their type is different.
You can also change the method signature by changing the order of method argument but that often leads to ambiguous code so better to be avoided.
Method Overriding
Method overriding is another way to define a method with the same name but different code and it must be in subclass.
Overriding is based upon run-time Polymorphism as method calls are resolved at run-time depending upon the actual object.
For example, if a variable of type Parent holds an object of Child class then the method invoked will be from child class and not parent class, provides its overridden.
In order to override a method, you must follow rules of method overriding which means declaring a method with the same signature in the subclass.
Method Hiding
A static method cannot be overridden in Java because their method calls are resolved at compile time but it didn't prevent you from declaring a method with the same name in a subclass.
In this case, we say that method in a subclass has a hidden static methods from the parent class.
If you have a case where the variable of Parent class is pointing to the object of Child class then also static method from Parent class is called because overloading is resolved at compile time.
Prevent Overriding a Method Without using the Final Keyword
There are some funky ways to prevent method overriding in Java. Though the final modifier is only for that purpose you can use a private keyword to prevent method overriding.
How? If you remember correctly, in order to override a method, the class must be extensible. If you make the constructor of parent class private then it's not possible to extend that class because its constructor will not be accessible in a subclass.
Which is automatically invoked by subclass constructor, hence it's not possible to override any method from that class.
This technique is used in the Singleton design pattern, where the constructor is purposefully made private and a static getInstance() method is provided to access singleton instance.
Override a Private Method
Co-Variant Method Overriding
One of the rules of method overriding is that return type of overriding method must be the same as an overridden method but this restriction is a relaxed little bit from Java 1.5 and now the overridden method can return a subclass of the return type of original method.
This relaxation is known as co-variant method overriding and it allows you to remove casting at the client end.
One of the best examples of this comes when you override the clone() method. Original Object.clone() method returns Object which needs to cast, but with co-variant method overriding you can directly return relevant type
E.g. Date class returns an object of java.util.Date instead of java.lang.Object.
Change Argument of Overriden Method
You cannot change the argument list of the overridden method in Java. An overriding method must have the same signature as the original method.
The only return type can be changed that to only to a subtype of the return type of original method.
Change Return Type of Method
You cannot change the return type of method during overriding. It would be a violation of the rules of overriding.
Though from Java 5 onward you can replace the return type with subtype e.g. if the original method has return type as java.lang.Object then you can change the return type of overridden method as any type e.g. clone() method.
This is also known as the co-variant method overriding in Java.
Difference Between Composition and Inheritance
There are several differences between Composition and Inheritance in Java, some of them are the following:
- The Composition is more flexible because you can change the implementation at runtime by calling setXXX() method, but Inheritance cannot be changed i.e. you cannot ask a class to implement another class at runtime.
- The composition builds HAS-A relationship while Inheritance builds IS-A relationship e.g. A Room HAS A Fan, but Mango IS-A Fruit.
- The parent-child relationship is best represented using Inheritance but If you just want to use the services of another class use Composition. For more differences see 5 reasons to favor composition over Inheritance.
Difference Between Polymorphism and Inheritance
Both Polymorphism and Inheritance go hand on hand, they help each other to achieve their goal.
Polymorphism allows flexibility, you can choose which code to run at runtime by overriding.
Difference Between Abstraction and Inheritance
Abstraction is an object-oriented concept which is used to simplify things by abstracting details.
It helps in the designing system. On the other hand, Inheritance allows code reuse. You can reuse the functionality you have already coded by using Inheritance
Difference Between Encapsulation and Inheritance
Inheritance is an object-oriented concept that creates a parent-child relationship. It is one of the ways to reuse the code written for parent class but it also forms the basis of Polymorphism.
On the other hand, Encapsulation is an object-oriented concept that is used to hide the internal details of a class e.g. HashMap encapsulate how to store elements and how to calculate hash values.
Difference Between Method Overloading and Overriding
The fundamental difference between overloading and overriding is that the former took place during compile time while later took place during run-time. Due to this reason.
It's only possible to overload virtual methods in Java. You cannot overload methods that are resolved during compile time e.g. private, static, and a final methods cannot be overridden in Java.
Also, rules of method overloading and overriding are different, for example in order to overload a method its method signature must be different but for the overriding method, it must be the same.
Difference Between super() and this() keyword
Super()
- Super keyword is used to call a constructor in the superclass.
- Super always refers to the parent of the current class
- Super allows you to access public/protected methods/attributes of the parent class. You cannot see the parent's private method/attributes.
- Super allows access to constructors from within the class' constructors only.
this()
- this refers to a reference to the current class.
- this allows access methods/attributes of the current class (including its own private methods/attributes).
- this is used to access the methods and fields of the current object. For this reason, it has no meaning in static methods, for example. this keyword used to call a constructor in the same class (other overloaded constructor)
The fundamental difference between overloading and overriding is that the former took place during compile time while later took place during run-time. Due to this reason.
It's only possible to overload virtual methods in Java. You cannot overload methods that are resolved during compile time e.g. private, static, and a final methods cannot be overridden in Java.
Also, rules of method overloading and overriding are different, for example in order to overload a method its method signature must be different but for the overriding method, it must be the same.
Difference Between super() and this() keyword
Super()
- Super keyword is used to call a constructor in the superclass.
- Super always refers to the parent of the current class
- Super allows you to access public/protected methods/attributes of the parent class. You cannot see the parent's private method/attributes.
- Super allows access to constructors from within the class' constructors only.
this()
- this refers to a reference to the current class.
- this allows access methods/attributes of the current class (including its own private methods/attributes).
- this is used to access the methods and fields of the current object. For this reason, it has no meaning in static methods, for example. this keyword used to call a constructor in the same class (other overloaded constructor)
Comments
Post a Comment