Inheritance in Java
Inheritance in Java
IN
JAVA
INHERITANCE
In Java, one class can easily inherit the attributes and
methods from some other class. This mechanism of
acquiring objects and properties from some other class
is known as inheritance in Java.
Inheritance is used to borrow properties & methods
from an existing class.
Inheritance helps us create classes based on existing
classes, which increases the code's reusability.
Important terminologies used in Inheritance :
1.Parent class/superclass: The class from which a class inherits
methods and attributes is known as parent class.
2.Child class/sub-class: The class that inherits some other class's
methods and attributes is known as child class.
Extends keyword in inheritance :
The extends keyword is used to inherit a subclass
from a superclass.
Syntax :
class Subclass-name extends Superclass-name
{
//methods and fields
}
Example :
public class dog extends Animal {
// code
}
Types of inheritance in Java.
JAVA CLASS DOES NOT SUPPORT MULTIPLE INHERITANCE
Why multiple inheritance is not
supported in Java class?
1) Abstract class can have abstract and non- Interface can have only abstract methods. Since Java 8,
abstract methods. it can have default and static methods also.
2) Abstract class doesn't support multiple Interface supports multiple inheritance.
inheritance.
3) Abstract class can have final, non-final, static and Interface has only static and final variables.
non-static variables.
4) Abstract class can provide the implementation of Interface can't provide the implementation of abstract
interface. class.
5) The abstract keyword is used to declare abstract The interface keyword is used to declare interface.
class.
6) An abstract class can extend another Java class An interface can extend another Java interface only.
and implement Java interfaces.
7) An abstract class can be extended using keyword An interface can be implemented using keyword
"extends". "implements".
8) A Java abstract class can have class members like Members of a Java interface are public by default.
private, protected, etc.