1 / 23

Encapsulation

Encapsulation. CMSC 202. Types of Programmers. Class programmers Developers of new classes Goal: Expose the minimum interface necessary to use a new class Implementation (code) is “hidden” Client programmers Write code (the client program ) that uses existing classes. Encapsulation.

addo
Download Presentation

Encapsulation

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Encapsulation CMSC 202

  2. Types of Programmers • Class programmers • Developers of new classes • Goal: Expose the minimum interface necessary to use a new class • Implementation (code) is “hidden” • Client programmers • Write code (the client program) that uses existing classes

  3. Encapsulation • Combining data and operations into a single entity (class) • Providing appropriate access control • Achieved through information hiding/abstraction Pre-coded Class X Class X interface Client Program Pre-coded Class Y Class Y interface

  4. The Value of Encapsulation • Client programmers do not need to know how the class is implemented, only how to use it. • Class implementation may be changed with no impact on code that uses the class. Client Program X Pre-coded Class X Class X interface Modified Class X Class X interface

  5. Class Interface • Instance variables • name • what it represents • type • Methods • name • what it does (not how) • pre & post-conditions • parameters • return value public String make; // car make public String model; // car model public int year; // car year /* Resets a car’s make * Preconditions: New make is non-null * Postconditions: Car’s make is reset * Parameters: Car’s new make * Returns: Nothing */ public void getMake(String newMake )

  6. Visibility Modifiers • Provide access control to class • instance variables • constants • methods • public – directly accessible by client code • private – accessible only by methods within the class (class scope) • Other – later Reference: http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

  7. Private Instance Variables Example public class Car { public String model; public String make; private int year; public void setYear(intnewYear){ year = newYear; } } public class CarDemo { public static void main(String[] args) { Car car = new Car(); car.make = “Toyota"; // OK car.model = “Prius"; // OK car.year = 2008; // compiler error car.setYear(2008); // OK } }

  8. Private Instance Variables: Summary • Only accessible within the class • Are notdirectly accessibleby a client program • Hide implementationdetails, promoting encapsulation • Good programming practice: • Label all instance variables as non-public (typically, private). • Bottom line: • The class should have complete control over how/when/if the instance variables are changed or accessed. Reference: http://docs.oracle.com/javase/tutorial/java/javaOO/variables.html

  9. Accessors and Mutators • Accessor method (getter) • Retrieves the value of a private instance variable • Conventions: • Start the method name with get. • Start edge case for booleans with is. • Mutator method (setter) • Changes the value of a private instance variable. • Convention: Start the method name with set. • Gives the client program indirect access to the instance variables.

  10. Why Accessors and Mutators? • Accessors • The class implementer decides • which instance variables will have accessors, and • in what form they will be returned. • Mutators • validate the new value of the instance variable, and • decide whether or not to actually make the requested change.

  11. Example Car Accessor and Mutator public class Car { private int year; // 4-digit year between 1000 and 9999 private String vin; // Vehicle identification number // Accessorto return the vin member public String getVin() { return vin; } // Mutatorto change the year member public booleansetYear(intnewYear) { if(newYear >= 1000 && newYear <= 9999) { year = newYear; return true; } return false; } // ... }

  12. Accessor/Mutator Caution • In general, do not provide accessors and mutators for all private instance variables. • Bottom line: Limit the class interface.

  13. Private Methods • Have class scope • Cannot be invoked by a client program • Used as “helper” methods to support top-down implementation of a public method. Reference: http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html

  14. Private Method Example public class Car { private int year; // 4-digit year between 1000 and 9999 // Helper method – class scope private booleanisValidYear(int year) { return(year >= 1000 && year <= 9999); } // Mutatorto change the year member public booleansetYear(intnewYear) { if(isValidYear(newYear)) { year = newYear; return true; } return false; } // ... }

  15. Encapsulation Summary • Combine methods and data in a single class. • Use private instance variables for information hiding. • Minimize the class’s public interface. Keep it secret, keep it safe

  16. Method Overloading

  17. Method Names • Different classes can define a method with the same name. • Example: • Java can determine which method to call based on the type of the calling object. Cat myCat = new Cat(); Dog myDog = new Dog(); System.out.println(myCat); System.out.println(myDog);

  18. Method Overloading • When two or more methods in the same class have the same name • Example: publicbooleansetStyle(String make, String model) publicbooleansetStyle(String make) Reference: http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html

  19. Car Class — Overloaded setStyle public class Car { // ... private String model; private String make; public booleansetStyle(String make, String model) { if(isValidMake(make) && isValidModel(model)) { this.make = make; this.model = model; return true; } return false; } public booleansetStyle(String make) { if(isValidMake(make)) { this.make = make; return true; } return false; } private booleanisValidMake(String make) { return make != null && !make.equals(""); } private booleanisValidModel(String model) { return model != null && !model.equals(""); } }

  20. CarDemo Class public class CarDemo { public static void main(String[] args) { Car car = new Car(); car.setStyle("Mazda"); System.out.println(car); car.setStyle("Audi", "A8"); System.out.println(car); } } How does Java know which setStyle method to call?

  21. Method Signature • A method is uniquely identified by its • name and • parameter list (types and order). • This is known as its signature. • Examples … public booleansetStyle(String make, String model) public booleansetStyle(int year, String make, String model) public booleansetStyle(String make, String model, String color) public booleansetStyle(int year, String color) public booleansetStyle(String make) Reference: http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html

  22. Return Type is Not Enough • Attempt to overload Car’s setStyle() method by using different return types: • This is NOT valid method overloading. • The method return value can be ignored. publicvoidsetStyle(String make) { /* code here */} publicbooleansetStyle(String model) { /* code here */ } car.setStyle("Mazda");

  23. Common Problem • Type coercion can confuse the compiler: • So now, • The Java compiler can’t decide whether to • promote 7 to 7.0 and call the first version of calculateAverage, or • promote 5 to 5.0 and call the second. • Solution: Cast the arguments so that they match one of the signatures. //version 1 publicdoublecalculateAverage(int a, double b) { /* code */ } //version 2 publicdoublecalculateAverage(double a, int b) { /* code */ } MathUtils math = newMathUtils(); math.calculateAverage(5, 7); // two intparameters math.calculateAverage(5, (double)7); OR Math.calculateAverage((double)5, 7);

More Related