How do you encapsulate properties in inheritance
Answer: In simple terms encapsulation means hide information or data hiding. Information that doesn’t need to be known to others in order to perform some task. Please have example below:
package com.javahonk.encapsulation; public class Women { private int age = 20; public void willGoOutWithMen(int age, String firstName, String lastName) { if (age >= 25) { System.out.println("Dear " + firstName + " " + lastName + " I don't like Men age above 25 \n"); } else { System.out.println("Dear " + firstName + " " + lastName + " I will come with you. \n"); } } public int getAge() { return age; } }
package com.javahonk.encapsulation; public class Men extends Women{ public static void main(String args[]){ Men men = new Men(); Women women = new Women(); // Ask for party if age is 26 women.willGoOutWithMen(26,"Java","Honk"); // Ask for party if age is 24 women.willGoOutWithMen(22,"Java","Monk"); // Men doesn't have access to Women age but he can ask her // We are hiding women age using private modifier men.askHerAge(); } private void askHerAge(){ System.out.println("Women age: "+getAge()); } }
Output: