1 / 33

CS 177

Week 11: Class Design. CS 177. Designing reusable classes. Most classes are meant to be used more than once This means that you have to think about what will be helpful for future programmers There are a number of trade-offs to consider More methods means more flexibility

duard
Download Presentation

CS 177

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. Week 11: Class Design CS 177

  2. Designing reusable classes • Most classes are meant to be used more than once • This means that you have to think about what will be helpful for future programmers • There are a number of trade-offs to consider • More methods means more flexibility • Too many methods can be confusing

  3. Documentation • Document thoroughly • Write documentation clearly in a way that describes what every method does • Input • Output • Expectations • The user probably will not be able to see your code • String API example: http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html

  4. Limited interfaces • Try to provide only the methods that are absolutely essential • Example: The Java Math library provides sin() and cos() methods but no sec() or cosec() methods • Stringhas lots of methods, and they are great • Usually, less is more

  5. Planning for the future • How do you make sure that your class does everything it will need to? • If you design a class to keep records about human beings, should you check to make sure that the age is in a certain range? • What range? • Make sure it’s less than 130 years? • Make sure it’s not negative?

  6. Classic failures in design • Y2K Bug • 2 digits for the date was not enough, now 4 • It’s all just going to get messed up in Y10K • Y2038 Bug • Unix machines often use a 32-bit integer to represent seconds since January 1, 1970 • Zip Codes (5+4) • Vehicle Identification Numbers • IP Addresses

  7. Designs with staying power? • IPv4 uses n1:n2:n3:n4 where each n is 0-255 (like 128.210.56.104) • That allows 232IP addresses (8.6 billion) • There are approximately 6.8 billion people on earth • IPv6 uses n1:n2:n3:n4:n5:n6:n7:n8 • 8 groups of 4 hexadecimal digits each • f7c3:0db8:85a3:0000:0000:8a2e:0370:7334 • How many different addresses is this? • 2128 ≈ 3.4×1038 is enough to have 500 trillion addresses for every cell of every person’s body on Earth • Will that be enough?!

  8. Objects have members • Members are the data inside objects • But, sometimes, wouldn’t it be nice if some data were linked to the class as a whole, rather than just one object? • What if you wanted to keep track of the total number of a particular kind of object you create?

  9. Static members • Static members are stored with the class, not with any particular object public class Item { private static intcount = 0; // only one copy (in class) private String name; // one copy per object public Item( String s ) { name = s; count++; // updates class counter } public String getName() { return name; } public static intgetTotalItems() { return count; } }

  10. Static rules • Static members are also called class variables • Static members can be accessed by either static methods or regular • Static members can be either public or private

  11. Members can be constant • Sometimes a value will not change after an object has been created: • Example: A ball has a single color after it is created • You can enforce the fact that the value will not change with the final keyword • A member declared final can only be assigned a value once • Afterwards, it can never change

  12. Constant example • Using final, we can fix the value of a member • It will only be set once, usually when the constructor is called • It is customary to use all caps for constant names public class Human { private String name; • private final String BIRTHPLACE; // never changes • private int age; public Human( String s, String whereBorn) { name = s; • BIRTHPLACE = whereBorn; age = 0; } public void birthPlaceChange(String locn) { • BIRTHPLACE = locn;// compile-time error! } }

  13. Static constants • It is possible to set a static member to be constant using the final keyword • Usually, this is used for global constants that will never ever change • Making these values public is reasonable • Since they never change, we never have to worry about a user corrupting the data inside of the object

  14. Static constant examples • The number of sides of a pentagon is always 5 • Other code can access this information by using the value Pentagon.SIDES • Exactly like Math.PI or Math.E public class Pentagon { privatedouble x; • privatedouble y; • public static final intSIDES = 5; // never changes • publicPentagon( doublenewX, doublenewY ) { x = newX; y = newY; } public double getX() { return x; } • public double getY() { return y; } }

  15. Design guidelines • Always think about future uses of your objects and classes • Hide as much data as possible (using private) • Make as much data as possible constant (using final) • Try to use the right number of methods • Short, powerful, intuitive methods • Don’t use redundant methods that do similar things • Check the input of all methods for errors

  16. Inheritance • The idea of inheritance is to take one class and generate a child class • This child class has everything that the parent class has (members and methods) • But, you can also add more functionality to the child • The child can be considered to be a specialized version of the parent

  17. Code reuse • The key idea behind inheritance is safe code reuse • You can use old code that was designed to, say, work with Vehicles, and apply that code Cars • All that you have to do is make sure that Car is a subclass (or child class) of Vehicle

  18. Creating a subclass • All this is well and good, but how do you actually create a subclass? • Let’s start by writing the Vehicle class public class Vehicle { … public void travel(String destination) { System.out.println(“Traveling to “ + destination); } }

  19. Extending a superclass • We use the extends keyword to create a subclass from a superclass • A Car can do everything that a Vehicle can, plus more public class Car extends Vehicle { private String model; public Car(String s) { model = s; } public String getModel() { return model; } public void startEngine() { System.out.println(“Vrooooom!”); } }

  20. Power of inheritance • There is a part of the Car class that knows all the Vehicle members and methods Car car = new Car(“Camry”); System.out.println( car.getModel() ); //prints “Camry” car.startEngine(); //prints “Vrooooom!” car.travel( “New York City” ); • //prints “Traveling to New York City”

  21. A look at a Car • Each Car object actually has a Vehicle object buried inside of it • If code tries to call a method that isn’t found in the Car class, it will look deeper and see if it is in the Vehicleclass Car model getModel() startEngine() Vehicle travel()

  22. Adding to existing classes is nice… • Sometimes you want to do more than add • You want to change a method to do something different • You can write a method in a child class that has the same signature as a method in a parent class • The child version of the method will always get called • This is called overriding a method

  23. Overriding example • We make the Boat class override the travel() method • In use: public class Boat extends Vehicle { public void travel(String destination) { • System.out.println(“Traveling across ” + • “the water to “ + destination); } } Boat b = new Boat(); b.travel(“Portugal”); // prints Traveling across the water to Portugal // even though v is a Vehicle reference

  24. Mammal example • We can define the Mammal class as follows: public class Mammal { public void makeNoise() { System.out.println(“Grunt!”); } }

  25. Mammal subclasses • From there, we can define the Dog, Cat, and Human subclasses, overriding the makeNoise() method appropriately public class Dog extends Mammal { public void makeNoise() { System.out.println(“Woof”); } } public class Cat extends Mammal { public void makeNoise() { System.out.println(“Meow”); } } public class Human extends Mammal { public void makeNoise() { System.out.println(“Hello”); } }

  26. Advanced student roster • We made a Student class last week • Each Student contained • First Name: String • Last Name: String • GPA: double • ID: int • We could make a GraduateStudent class adding: • Degree : String • Advisor: String

  27. class Student • public class Student • { • private String firstName; • private String lastName; • private double gpa; • private int id; • public Student() // default constructor • { • firstName = “”; • lastName = “”; • gpa = 0.0; • id = 0; • } • No matter how complex a program is, inside this method, only x, y, and z variables exist

  28. class Student (cont.) • public Student(String first, String last, double grades, int num) // constructor • { • firstName = first; • lastName = last; • gpa = grades; • id = num; • } • public double getGPA() // accessor • { • return gpa; • } • No matter how complex a program is, inside this method, only x, y, and z variables exist

  29. class Student (cont.) public intgetID() // accessor { return id; } public String getName() // accessor { return lastName + “, “ + firstName; } • No matter how complex a program is, inside this method, only x, y, and z variables exist

  30. class Student (cont.) public void setGPA(double grades) // mutator { if (grades>=0.0 && grades<=4.0) gpa = grades; else System.out.println(“Incorrect GPA”); } public void setID(int num) // mutator { if (num>=0 && num<=99999) id = num; else System.out.println(“Incorrect ID”); } • No matter how complex a program is, inside this method, only x, y, and z variables exist

  31. class GraduateStudent • public class GraduateStudent extends Student • { • private String degree; • private String advisor; • public GraduateStudent() // default • { • super(); • degree = “”; • advisor = “”; • } • No matter how complex a program is, inside this method, only x, y, and z variables exist

  32. class GraduateStudent(cont.) • public GraduateStudent(String first, String last, double grades, int num, String deg, String adv) // constructor • { • super (first, last, grades, num); • degree = deg; • advisor = adv; • } • public String getDegree() // accessor • { • return degree; • } • No matter how complex a program is, inside this method, only x, y, and z variables exist

  33. class GraduateStudent(cont.) public String getAdvisor() // accessor { return advisor; } public void setDegree(String deg) // mutator { if (deg==“PhD” || deg==“MS”) degree = deg; else System.out.println(“Incorrect Degree”); } • No matter how complex a program is, inside this method, only x, y, and z variables exist

More Related