Encapsulation and public | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 1

Encapsulation and public

Please give an example of practical use of public and encapsulation

2nd Jun 2017, 5:30 PM
Legend Shees
Legend Shees - avatar
1 Answer
+ 2
Encapsulation is basically using private variables with methods to modify or receive them. Instead of using a public variable. class Person{ private String name; private int age: Person(String name, int age){ this.name = name; this.age = age; } public void birthday(){ this.age++; } public int getAge(){ return this.age; } public int getName(){ return this.name; } } Another example: class Animals{ private Animal[] allAnimals; // notice its private /* pretend I had a constructor to initialize allAnimals.*/ // so this is how I will get it public Animal[] getAllAnimals(){ return allAnimals; } } abstract class Animal{}
2nd Jun 2017, 8:11 PM
Rrestoring faith
Rrestoring faith - avatar