/
CS 177 Week  11:  Class CS 177 Week  11:  Class

CS 177 Week 11: Class - PowerPoint Presentation

pamella-moone
pamella-moone . @pamella-moone
Follow
342 views
Uploaded On 2019-06-23

CS 177 Week 11: Class - PPT Presentation

Design 1 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 tradeoffs to consider ID: 760104

Share:

Link:

Embed:

Download Presentation from below link

Download Presentation The PPT/PDF document "CS 177 Week 11: Class" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.


Presentation Transcript

Slide1

CS 177

Week 11: Class Design

1

Slide2

Designing reusable classes

Most classes are meant to be used more than onceThis means that you have to think about what will be helpful for future programmersThere are a number of trade-offs to considerMore methods means more flexibilityToo many methods can be confusing

2

Slide3

Documentation

Document thoroughlyWrite documentation clearly in a way that describes what every method doesInputOutputExpectationsThe user probably will not be able to see your codeString API example: http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html

3

Slide4

Limited interfaces

Try to provide only the methods that are absolutely essentialExample: The Java Math library provides sin() and cos() methods but no sec() or cosec() methodsString has lots of methods, and they are greatUsually, less is more

4

Slide5

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?

5

Slide6

Classic failures in design

Y2K Bug2 digits for the date was not enough, now 4It’s all just going to get messed up in Y10KY2038 BugUnix machines often use a 32-bit integer to represent seconds since January 1, 1970Zip Codes (5+4)Vehicle Identification NumbersIP Addresses

6

Slide7

Designs with staying power?

IPv4 uses n1:n2:n3:n4 where each n is 0-255 (like 128.210.56.104)

That allows 232 IP addresses (8.6 billion)There are approximately 6.8 billion people on earthIPv6 uses n1:n2:n3:n4:n5:n6:n7:n88 groups of 4 hexadecimal digits eachf7c3:0db8:85a3:0000:0000:8a2e:0370:7334How 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 EarthWill that be enough?!

7

Slide8

Objects have members

Members are the data inside objectsBut, 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?

8

Slide9

Static members

Static members are stored with the class, not with any particular object

public class Item { private static int count = 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 int getTotalItems() { return count; }}

9

Slide10

Static rules

Static members are also called class variablesStatic members can be accessed by either static methods or regularStatic members can be either public or private

10

Slide11

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 createdYou can enforce the fact that the value will not change with the final keywordA member declared final can only be assigned a value onceAfterwards, it can never change

11

Slide12

Constant example

Using final, we can fix the value of a memberIt will only be set once, usually when the constructor is calledIt 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! }}

12

Slide13

Static constants

It is possible to set a static member to be constant using the final keywordUsually, this is used for global constants that will never ever changeMaking these values public is reasonableSince they never change, we never have to worry about a user corrupting the data inside of the object

13

Slide14

Static constant examples

The number of sides of a pentagon is always 5Other code can access this information by using the value Pentagon.SIDESExactly like Math.PI or Math.E

public class Pentagon { private double x; private double y; public static final int SIDES = 5; // never changes public Pentagon( double newX, double newY ) { x = newX; y = newY; } public double getX() { return x; } public double getY() { return y; }}

14

Slide15

Design guidelines

Always think about future uses of your objects and classesHide as much data as possible (using private)Make as much data as possible constant (using final)Try to use the right number of methodsShort, powerful, intuitive methodsDon’t use redundant methods that do similar thingsCheck the input of all methods for errors

15

Slide16

Inheritance

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

16

Slide17

Code reuse

The key idea behind inheritance is safe code reuseYou can use old code that was designed to, say, work with Vehicles, and apply that code CarsAll that you have to do is make sure that Car is a subclass (or child class) of Vehicle

17

Slide18

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); }}

18

Slide19

Extending a superclass

We use the extends keyword to create a subclass from a superclassA 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!”); } }

19

Slide20

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”

20

Slide21

A look at a Car

Each Car object actually has a Vehicle object buried inside of itIf 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 Vehicle class

Car

modelgetModel()startEngine()

Vehicletravel()

21

Slide22

Adding to existing classes is nice…

Sometimes you want to do more than addYou want to change a method to do something differentYou can write a method in a child class that has the same signature as a method in a parent classThe child version of the method will always get calledThis is called overriding a method

22

Slide23

Overriding example

We make the Boat class override the travel() methodIn 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

23

Slide24

Mammal example

We can define the Mammal class as follows:

public class Mammal { public void makeNoise() { System.out.println(“Grunt!”); }}

24

Slide25

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”); }}

25

Slide26

Advanced student roster

We made a Student class last weekEach Student containedFirst Name: StringLast Name: StringGPA: doubleID: intWe could make a GraduateStudent class adding:Degree : StringAdvisor: String

26

Slide27

class Student

No matter how complex a program is, inside this method, only x, y, and z variables exist

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; }

27

Slide28

class Student (cont.)

No matter how complex a program is, inside this method, only x, y, and z variables exist

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; }

28

Slide29

class Student (cont.)

No matter how complex a program is, inside this method, only x, y, and z variables exist

public int getID() // accessor { return id; }public String getName() // accessor { return lastName + “, “ + firstName; }

29

Slide30

class Student (cont.)

No matter how complex a program is, inside this method, only x, y, and z variables exist

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”); }

30

Slide31

class GraduateStudent

No matter how complex a program is, inside this method, only x, y, and z variables exist

public class GraduateStudent extends Student{ private String degree; private String advisor; public GraduateStudent() // default { super(); degree = “”; advisor = “”;}

31

Slide32

class GraduateStudent (cont.)

No matter how complex a program is, inside this method, only x, y, and z variables exist

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; }

32

Slide33

class GraduateStudent (cont.)

No matter how complex a program is, inside this method, only x, y, and z variables exist

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”); }

33