- 1
Encapsulation and public
Please give an example of practical use of public and encapsulation
1 Respuesta
+ 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{}