What is the difference between Inheritance and Encapsulation?

Aayush Jaiswal
Aayush Jaiswal

Posted On: Jan 08, 2021

 

InheritanceEncapsulation
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; 
} 
}

    Related Questions

    Please Login or Register to leave a response.

    Related Questions

    Java inheritance interview questions

    Explain Inheritance in Java?

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

    Java inheritance interview questions

    Enlist diffrent types of Inheritance supported by Java?

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

    Java inheritance interview questions

    Are static members inherited to sub classes?

    Yes! static members are inherited to sub classes.  ...