Java – Inheritance

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object.

The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also.

In Java, every class implicitly extends the java.lang.Object class

keyword: extends

class Subclass-name extends Superclass-name
{
//methods and fields
}

The Super class is similar as a Parent or a Base class and the Sub class is similar to a Child or Derived class.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

When the child class object is instantiated, the JVM automatically instantiates its Parent class first and then it instantiates the child class.

Types of Inheritance:

  1. Single Inheritance: When a class inherits another class, it is known as a single inheritance.

  2. Multilevel Inheritance: When there is a chain of inheritance, it is known as multilevel inheritance.

  3. Hierarchical Inheritance: When two or more classes inherits a single class, it is known as hierarchical inheritance.

Method Overriding: Method Overriding happens when method in child class with same exact signature of the parent class.

Rules for Java Method Overriding

  1. The method must have the same name as in the parent class
  2. The method must have the same parameter as in the parent class.
  3. There must be an IS-A relationship (inheritance).

By using @Override, instead of getting a logical error we get a compile time error.

Super Keyword: Super keyword allows us to access the parent’s methods from within a child class.

Super Method: Super Method is used to invoke the parent class constructor. The super method invocation must be first line in the child class constructor.

Constructor Chaining: Using super and this methods, we can access more than one constructor of the child and parent in a single object creation.

原文链接:Java – Inheritance

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容