Advertisement
Guest User

[Java] Encapsulation Example

a guest
Dec 8th, 2019
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.19 KB | None | 0 0
  1. // -EXAMPLE CODE, CONCEPT ONLY-
  2.  
  3. //Encapsulation is the idea that properties of objects should be insulated from unnecessary access. Every
  4. //interaction should go through a method of the object! Notice that typeOfCar is public! Anyone can change!
  5. //Should be private and use the getters and setters to modify the values.
  6.  
  7. Class Car{
  8.     //Should probably not be public, or anyone can change it.
  9.     public String typeOfCar;
  10.    
  11.     //Default constructor
  12.     public Car(){
  13.         this.typeOfCar = "Scooter";
  14.     }
  15.    
  16.     //This constructor takes a String as an argument to define the type of car
  17.     public Car(String type){
  18.         this.typeOfCar = type;
  19.     }
  20.    
  21.     //This method returns the type of car
  22.     public String getType(){
  23.         return this.typeOfCar;
  24.     }
  25.  
  26.     //This method sets the type of car
  27.     public void setType(String type){
  28.         this.typeOfCar = type;
  29.     }
  30. }
  31.  
  32. int Main(){
  33.     Car myCar = new Car("Ice Cream Truck");
  34.  
  35.     System.out.println("My car is a " + myCar.getType()); //Outputs "Ice Cream Truck"
  36.  
  37.     //Should not be exposed! Anything with access can change the car type! Should use setter instead.
  38.     myCar.typeOfCar = "Goat";
  39.  
  40.     System.out.println("My car is a " + myCar.getType()); //Now outputs "Goat"
  41.  
  42.     return 0;
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement