Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // -EXAMPLE CODE, CONCEPT ONLY-
- //Encapsulation is the idea that properties of objects should be insulated from unnecessary access. Every
- //interaction should go through a method of the object! Notice that typeOfCar is public! Anyone can change!
- //Should be private and use the getters and setters to modify the values.
- Class Car{
- //Should probably not be public, or anyone can change it.
- public String typeOfCar;
- //Default constructor
- public Car(){
- this.typeOfCar = "Scooter";
- }
- //This constructor takes a String as an argument to define the type of car
- public Car(String type){
- this.typeOfCar = type;
- }
- //This method returns the type of car
- public String getType(){
- return this.typeOfCar;
- }
- //This method sets the type of car
- public void setType(String type){
- this.typeOfCar = type;
- }
- }
- int Main(){
- Car myCar = new Car("Ice Cream Truck");
- System.out.println("My car is a " + myCar.getType()); //Outputs "Ice Cream Truck"
- //Should not be exposed! Anything with access can change the car type! Should use setter instead.
- myCar.typeOfCar = "Goat";
- System.out.println("My car is a " + myCar.getType()); //Now outputs "Goat"
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement