Posted On: Dec 21, 2022
The major difference between Inheritance and Encapsulation are as follows -
Inheritance | Encapsulation |
---|---|
Inheritance is the process or mechanism by which you can acquire the properties and behavior of a class into another class. | Encapsulation refers to the winding of data into a single unit which is known as class. |
Inheritance indicates that a child class (subclass) inherits all the attributes and methods from a parent class (superclass). | Encapsulation indicates that one class must not have access to the (private) data of another class. |
/* Following is an example that demonstrates how to achieve Inheritance in Java */class Animal{ void eat(){ System.out.println("eating..."); } } class Dog extends Animal{ void bark(){ System.out.println("barking..."); } } class TestInheritance{ public static void main(String args[]){ Dog d=new Dog(); d.bark(); d.eat(); } } | /* Following is an example that demonstrates how to achieve Encapsulation in Java */public class EncapTest { private String name; private String idNum; private int age; public int getAge() { return age; } public String getName() { return name; } public String getIdNum() { return idNum; } public void setAge( int newAge) { age = newAge; } public void setName(String newName) { name = newName; } public void setIdNum( String newId) { idNum = newId; } } |
Never Miss an Articles from us.
Inheritance is one of the most important pillars of the OOPs (Object Oriented programming system). Inheritance in Java is a mechanism by which one class acquires all the properties and behaviors of an...
The various kinds of inheritance supported by Java.Single Inheritance: Single Inheritance is the easy inheritance of all, while a group lengthens another group (Simply one class) then one cal...
Yes! static members are inherited to sub classes. ...