240 likes | 256 Views
Announcements. Your resources include me (your instructor) the TAs and consultants cornell.class.cs100 http://www.cs.cornell.edu/cs100-su99/ email! No class on Monday. Today’s Topics. Review One whole program Inheritance Constructors of superclasses Access modifier protected
E N D
Announcements • Your resources include • me (your instructor) • the TAs and consultants • cornell.class.cs100 • http://www.cs.cornell.edu/cs100-su99/ • email! • No class on Monday Lecture 5
Today’s Topics • Review • One whole program • Inheritance • Constructors of superclasses • Access modifier protected • Overriding methods • The method toString() for all classes Lecture 5
Review • Public and private? • What does (s1 == s2) indicate if s1 and s2 are strings? • Difference between procedure and function? • What’s a constructor good for? Lecture 5
A Whole Program Indicate that we want to be be able to use any class in package java.io Note: java.lang is always automatically imported. That’s where system.out.println comes from, for example import java.io.*; public class Rectangle{ public int width; public int length; public Rectangle(int side1, int side2) { width = side1; length = side2; } public int area() { return(length * width); } } Lecture 5
Rest of Program public class TrivialApplication { public static void main(String args[]) throws IOException { BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in)) int userWidth = 0; int userLength = 0; System.out.println("Width of your rectangle?"); userWidth = Integer.parseInt(stdin.readLine()); System.out.println("Length of your rectangle?"); userLength = Integer.parseInt(stdin.readLine()); Rectangle r = new Rectangle(userWidth, userLength); System.out.print("In a rectangle of width " + userWidth); System.out.print(" and length " + userLength + " the area is "); System.out.println(r.area()); try { System.in.read(); // prevent console window from going away } catch (java.io.IOException e) {} } } Lecture 5
Deconstruction A class definition public class TrivialApplication { public static void main(String args[]) throws IOException { BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in)) Ignore this for now, used when taking args from the commandline We’ll discuss exceptions later An object created to help with I/O Lecture 5
Inheritance -- Briefly • A subclass B of class A inherits fields and methods from class A • A is a super-class of B • In Java, the keyword extends is used to define a subclass Lecture 5
Method toString() • // Yield a string containing the data for // that person • public String toString(){ return name + “ ” + salary + “ ” + hiredate;} • Actually, every class implements method toString • Note: in <string> + B, if B is not a string, B.toString is used to convert it. Lecture 5
Recall the class Employee. . . // An instance of Employee contains a person's name, // salary, and year hired. It has a constructor and // methods for raising the salary, printing the data, and // retrieving the person's name and the year hired. public class Employee { public String name; // The person's name publicdouble pay; // The person's yearly salary publicint hireDate; // The year hired Lecture 5
// Constructor: a person with name n, salary // s and year d hiredpublic Employee(String n, double s, int d){ name = n; pay = s; hireDate = d;} // Raise the pay by p percent publicvoid raiseSalary(double p) {pay= pay * (1 + p/100.0);} // Yield the year the person was hired publicint hireYear() {return hireDate;} Lecture 5
// Yield the person's name public String getName() {return name;} // Yield a String containing person’s data public String toString() { String s= name; s= s + " " + pay + " " + hireDate; return s;} } • This was the old class Employee Lecture 5
Today’s Task • Modify class Employee to take into account 3 different kinds: • VIP -- Need a field bonus. Get a yearly salary • Salaried -- Expected to work overtime without extra pay • Regular -- Hourly wage instead of yearly salary, have time cards. Could record # hours worked each week, but will assume 40 Lecture 5
How to add these things? Add fields? • int employeeKind; // VIP = 1, salaried = 2 // regular = 3 • double bonus; // bonus for VIP only • double hourlyWage; // for regular emp only • // method to set bonus if employee is VIPpublic setBonus(double b) { if (employeeKind == 1) bonus = b; } • Many other changes required. . . Lecture 5
Problems • Now each employee has a field for bonus and hourly wage but not all employees need these fields • Have to test to determine what kind of employee is being processed within many of the methods. This produces ugly code. • What if a new kind of employee is added (VVIP)? Everything has to change again Lecture 5
Better Solution -- Inheritance public class VIP extends Employee { private double bonus; // the VIP’s bonus // Constructor: person with name n, // year d hired, pay s and bonus b public VIP(String n, int d, double s, double b) { super(n, d); pay = s; bonus = b; } Lecture 5
Other Methods in class VIP // Yield a string containing datapublic String toString(){ return “VIP” + “ “ name + “ “ + pay + “ “ + “ “ + bonus + “ “ + hireDate; }// Change bonus to ppublic void changeBonus(double p) { bonus = p; } Lecture 5
What’s Going on? • An instance of class VIP has • every field that the class Employee has • plus the ones VIP declares • every method that the class Employee has. . . • . . .except those that are overridden Lecture 5
Employee x Name Millett pay 0 hireDate 1999 Employee, hireYear, getName, toString VIP extends Employee Employee x; x = new Employee(“Millett”, 1999); Employee y = new VIP(“Buck”, 1999, 100000, 1000); VIP y Name Buck pay 100000 hireDate 1999 Employee, hireYear, getName, toString bonus 1000 VIP changeBonus Lecture 5
super • For an instance of VIP, a constructor of the super-class Employee should be called to initialize the fields declared in Employee. • This is the first statement in a constructor for VIP super(n, d); • This of this as equivalent to Employee(n, d) Lecture 5
Protected/Public/Private • If fields of Employee are public, they can be referenced from anywhere. • If they are private, they can be referenced only from instances of Employee. • If they are protected, they can be referenced only in same package --concept discussed much later!!! Lecture 5
Methods in sub/super-classes VIP y; y= new VIP(“Perkins”, 1983, 90000, 1000); y.getName() refers to method getName of its superclass, Employee. This is because getName is not defined in VIP. y.getBonus() refers to method getBonus of VIP. This is because getBonus is defined in VIP. y.toString() refers to method toString of VIP. This is because toString is defined in VIP. Method toString of superclass Employee has been overridden in class VIP. Lecture 5
Intuitively, Inheritance. . . • Derive a new class from an existing class • Purpose: Software re-use • The “is-a” relationship. The subclass “is a” more specific version of the superclass • e.g. VIP “is a” Employee Lecture 5
Encapsulation • Objects are black boxes -- ultimately, we don’t want to worry about how they work • Other things interact with object through “service methods” • An object should be self-governing (variables can only be modified w/in the object itself) Lecture 5
Discussion Questions • Can source code be censored? • Who is responsible if a system fails? • Is programming necessarily a solitary pursuit? Lecture 5