Presentation is loading. Please wait.

Presentation is loading. Please wait.

Unit 7 Textbook Chapter 9.

Similar presentations


Presentation on theme: "Unit 7 Textbook Chapter 9."— Presentation transcript:

1 Unit 7 Textbook Chapter 9

2 The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs. Large-scale projects face many issues: getting many programmers to work together getting code finished on time avoiding redundant code finding and fixing bugs maintaining, improving, and reusing existing code code reuse: The practice of writing program code once and using it in many contexts.

3 Object-Oriented Languages - OOP
For a whirlwind tour of OOP, an object-oriented language is supposed to include three major concepts: Encapsulation - is the ability to hide and protect data. Covered in Unit 6 Inheritance - lets you design a class by deriving it from an existing one. This feature allows you to reuse existing code without doing copy and paste. Covered today Polymorphism - that there can be different forms of the same thing, so that you could have one variable that could store several different types of objects; or a method that accepts no arguments and another method with the exact same name that accepts an integer argument (and maybe another that accepts a string and a double-precision argument, etc.). Covered next class

4 Inheritance inheritance: A way to form new classes based on existing classes, taking on their attributes/behavior. a way to group related classes a way to share code between two or more classes One class can extend another, absorbing its data/behavior. superclass: The parent class that is being extended. subclass: The child class that extends the superclass and inherits its behavior. Subclass gets a copy of every field and method from superclass

5 Inheritance syntax By extending Car, each ElectricCar object now:
public class name extends superclass { Example: public class ElectricCar extends Car { ... } By extending Car, each ElectricCar object now: receives a xpos, ypos, direction, radioVolumeLevel, fuelState private fields and turn, drive, addFuel, changeRadioVolume, and getRadioVolume methods automatically can be treated as an Car by client code (seen later)

6 The Object Class The Object class sits at the top of the class hierarchy tree in the Java development environment. Every class in the Java system is a descendent (direct or indirect) of the Object class. The Object class defines the basic state and behavior that all objects must have, such as the ability to compare oneself to another object, to convert to a string, to wait on a condition variable, to notify other objects that a condition variable has changed, return the object's class.

7 The Object Class cont. Everything in Java is a class. If a class has fields that are instance variables, then they are stored inside dynamically allocated objects created by new to represent instances of the class. However, when Java documentation uses the name "Object" capitalized like a proper name, then it is referencing a special class built into the language. The Object class is the parent of all other classes. When any new class definition omits the extends keyword, it implicitly extends the Object class. A reference variable declared to designate member of the Object class can actually point to any dynamically allocated object from any class.

8 Overriding methods override: To write a new version of a method in a subclass that replaces the superclass's version. No special syntax required to override a superclass method. Just write a new version of it in the subclass. public class ElectricCar extends Car { // overrides toString method in Car/Object class public String toString() { return “Electric: State of Charge: “ + charge; } ...

9 Class Object All types of objects have a superclass named Object.
Every class implicitly extends Object The Object class defines several methods: public String toString() Returns a text representation of the object, often so that it can be printed. public boolean equals(Object other) Compare the object to any other for equality. Returns true if the objects have equal state.

10 Recall: comparing objects
The == operator does not work well with objects. == compares references to objects, not their state. It only produces true when you compare an object to itself. Point p1 = new Point(5, 3); Point p2 = new Point(5, 3); if (p1 == p2) { // false System.out.println("equal"); } ... x 5 y 3 p1 ... p2 x 5 y 3

11 The equals method The equals method compares the state of objects.
if (str1.equals(str2)) { System.out.println("the strings are equal"); } But if you write a class, its equals method behaves like == if (p1.equals(p2)) { // false :-( System.out.println("equal"); This is the behavior we inherit from class Object. Java doesn't understand how to compare Points by default.

12 Flawed equals method We can change this behavior by writing an equals method. Ours will override the default behavior from class Object. The method should compare the state of the two objects and return true if they have the same x/y position. A flawed implementation: public boolean equals(Point other) { if (x == other.x && y == other.y) { return true; } else { return false; }

13 Flaws in our method The body can be shortened to the following:
return x == other.x && y == other.y; It should be legal to compare a Point to any object (not just other Points): // this should be allowed Point p = new Point(7, 2); if (p.equals("hello")) { // false ... equals should always return false if a non-Point is passed.

14 equals and Object public boolean equals(Object name) {
statement(s) that return a boolean value ; } The parameter to equals must be of type Object. Object is a general type that can match any object. Having an Object parameter means any object can be passed. If we don't know what type it is, how can we compare it?

15 Type-casting objects Solution: Type-cast the object parameter to a Point. public boolean equals(Object o) { Point other = (Point) o; return x == other.x && y == other.y; } Casting objects is different than casting primitives. Really casting an Object reference into a Point reference. Doesn't actually change the object that was passed. Tells the compiler to assume that o refers to a Point object.

16 Another flawed version
Another flawed equals implementation: public boolean equals(Object o) { return x == o.x && y == o.y; } It does not compile: Point.java:36: cannot find symbol symbol : variable x location: class java.lang.Object ^ The compiler is saying, "o could be any object. Not every object has an x field."

17 The instanceof keyword
if (variable instanceof type) { statement(s); } Asks if a variable refers to an object of a given type. Used as a boolean test. String s = "hello"; Point p = new Point(); expression result s instanceof Point false s instanceof String true p instanceof Point p instanceof String p instanceof Object s instanceof Object null instanceof String null instanceof Object

18 Final equals method // Returns whether o refers to a Point object with
// the same (x, y) coordinates as this Point. public boolean equals(Object o) { if (o instanceof Point) { // o is a Point; cast and compare it Point other = (Point) o; return x == other.x && y == other.y; } else { // o is not a Point; cannot be equal return false; }

19 Summary What is inheritance? What class does every class inherit from?
A way to form new classes based on existing classes, taking on their attributes/behavior. a way to group related classes a way to share code between two or more classes Why use inheritance? Code reuse What class does every class inherit from? Object What does it mean to override a method? To write a new version of a method in a subclass that replaces the superclass's version. How do you compare two objects? equals method How do you determine the type of an object? instanceof method

20 Inheritance – Exercise
Background This assignment demonstrates the notion of inheritance using Java. Your boss has requested that you design an application that needs a Car class. Later that same day, the designers tell you that you now need a Truck class. Your gut tells you that they will probably want a golf cart class by the end of the week. How can you leverage the common pieces of these three types of objects by using one generic base class? Objective for this Lab You are going to create four small Java classes; a driver class that has the static main method, a regular Java class named Vehicle, then two classes named Car and Truck, respectively that inherit from Vehicle class. Driver Your Test Harness class with the static main method Vehicle Your generic primary super class Car Your car class that inherits the vehicle class Truck Your truck class that inherits the vehicle class

21 Inheritance – Exercise Cont.
Required Methods Your application needs the following methods. start() stop() turn() getSpeed() setSpeed() increaseSpeed() decreaseSpeed() openTrunk() closeTrunk() openTailgate() closeTailgate() The generic Vehicle only contains the generic methods, start, stop, getSpeed, etc. The Car class contains the trunk methods and the Truck class contains the tailgate methods. Most methods simply need to display a simple message so you know it is being executed, like this: public void stop() { System.out.println("Stopping"); } The setSpeed, getSpeed and increaseSpeed methods need a little Java code to set instance variables.

22 Learning Objectives Create a method that uses the super keyword.
Develop a constructor that calls its superclass’s constructor. Differentiate between inheritance and polymorphism.

23 Review from last class What is inheritance?
A way to form new classes based on existing classes, taking on their attributes/behavior. a way to group related classes a way to share code between two or more classes Why use inheritance? Code reuse What class does every class inherit from? Object What does it mean to override a method? To write a new version of a method in a subclass that replaces the superclass's version.

24 Calling overridden methods
Subclasses can call overridden methods with super super.method(parameters) Example: public class Tabby extends Cat { public String toString(){ return "Tabby"; } public String makeSound(){ return super.makeSound() + " and Meowww";

25 Inheritance and constructors
When you add a constructor to the superclass that has parameters, your subclasses may not compile. For example, public Animal(int age) { this.age = age; } Implicit super constructor Animal() is undefined for default constructor. Must define an explicit constructor The short explanation: Once we write a constructor (that requires parameters) in the superclass, we must now write constructors for our subclasses as well. The long explanation: (next slide)

26 The detailed explanation
Constructors are not inherited. Subclasses don't inherit the Animal(int) constructor. Subclasses receive a default constructor that contains: public Dog() { super(); // calls Animal() constructor } But our Animal(int) replaces the default Animal(). The subclasses' default constructors are now trying to call a non-existent default Animal constructor.

27 Calling superclass constructor
super(parameters); Example: public class Lawyer extends Employee { public Lawyer(int years) { super(years); // calls Employee constructor } ... The super call must be the first statement in the constructor. Exercise: Make a similar modification to the Marketer class.

28 Polymorphism Why use it? Create extensible programs
So that your program can more easily handle future changes Possibly, reduce the quantity of required code

29 Polymorphism polymorphism: Ability for the same code to be used with different types of objects and behave differently with each. System.out.println can print any type of object. Each one displays in its own way on the console. CritterMain can interact with any type of critter. Each one moves, fights, etc. in its own way.

30 Coding with polymorphism
A variable of type T can hold an object of any subclass of T. Animal skyWireFox= new Dog(); You can call any methods from the Animal class on skyWireFox. When a method is called on critter, it behaves as a Dog. System.out.println(skyWireFox); // Woof

31 Polymorphism and parameters
You can pass any subtype of a parameter's type. public class EmployeeMain { public static void main(String[] args) { Lawyer lisa = new Lawyer(); Secretary steve = new Secretary(); printInfo(lisa); printInfo(steve); } public static void printInfo(Employee empl) { System.out.println("salary: " + empl.getSalary()); System.out.println("v.days: " + empl.getVacationDays()); System.out.println("v.form: " + empl.getVacationForm()); System.out.println(); OUTPUT: salary: salary: v.days: 15 v.days: 10 v.form: pink v.form: yellow

32 Polymorphism and arrays
Arrays of superclass types can store any subtype as elements. public class EmployeeMain2 { public static void main(String[] args) { Employee[] e = { new Lawyer(), new Secretary(), new Marketer(), new LegalSecretary() }; for (int i = 0; i < e.length; i++) { System.out.println("salary: " + e[i].getSalary()); System.out.println("v.days: " + e[i].getVacationDays()); System.out.println(); } Output: salary: v.days: 15 v.days: 10 salary: salary:

33 Polymorphism problems
4-5 classes with inheritance relationships are shown. A client program calls methods on objects of each class. You must read the code and determine the client's output. Look for this on an exam near you.

34 A polymorphism problem
Suppose that the following four classes have been declared: public class Foo { public void method1() { System.out.println("foo 1"); } public void method2() { System.out.println("foo 2"); public String toString() { return "foo"; public class Bar extends Foo { System.out.println("bar 2"); public class Baz extends Foo { System.out.println("baz 1"); return "baz"; public class Mumble extends Baz { System.out.println("mumble 2"); What would be the output of the following client code? Foo[] pity = {new Baz(), new Bar(), new Mumble(), new Foo()}; for (int i = 0; i < pity.length; i++) { System.out.println(pity[i]); pity[i].method1(); pity[i].method2(); System.out.println();

35 Polymorphism answer Output: baz baz 1 foo 2 foo foo 1 bar 2 mumble 2
Foo[] pity = {new Baz(), new Bar(), new Mumble(), new Foo()}; for (int i = 0; i < pity.length; i++) { System.out.println(pity[i]); pity[i].method1(); pity[i].method2(); System.out.println(); } Output: baz baz 1 foo 2 foo foo 1 bar 2 mumble 2

36 Diagramming the classes
Add classes from top (superclass) to bottom (subclass). Include all inherited methods.

37 Finding output with tables
method Foo Bar Baz Mumble method1 foo 1 baz 1 method2 foo 2 bar 2 mumble 2 toString foo baz method Foo Bar Baz Mumble method1 foo 1 baz 1 method2 foo 2 bar 2 mumble 2 toString foo baz method Foo Bar Baz Mumble method1 method2 toString It's annoying to flip back and forth between slides here. I suggest putting the classes into a text editor so you can switch windows back and forth to fill in the table.

38 Summary What keyword do you use to call methods in the superclass?
i.e. super.makeSound(); When you add a constructor with parameters to the superclass, why do you get a compiler error in your subclasses? Subclasses don't inherit the parameter constructor. Subclasses get a constructor that calls the superclass parameter less constructor, which doesn’t exist now. What is polymorphism? Ability for the same code to be used with different types of objects and behave differently with each.

39 Review What is inheritance? What is polymorphism?
A way to form new classes based on existing classes, taking on their attributes/behavior. a way to group related classes a way to share code between two or more classes Why use inheritance? Code reuse What is polymorphism? Ability for the same code to be used with different types of objects and behave differently with each.

40 Interfaces

41 Write a set of Circle, Rectangle, and Triangle classes.
Relatedness of types Write a set of Circle, Rectangle, and Triangle classes. Certain operations that are common to all shapes. perimeter - distance around the outside of the shape area - amount of 2D space occupied by the shape Every shape has them but computes them differently.

42 Shape area, perimeter Rectangle (as defined by width w and height h):
area = w h perimeter = 2w + 2h Circle (as defined by radius r): area =  r2 perimeter = 2  r Triangle (as defined by side lengths a, b, and c) area = √(s (s - a) (s - b) (s - c)) where s = ½ (a + b + c) perimeter = a + b + c

43 Common behavior Write shape classes with methods perimeter and area.
We'd like to be able to write client code that treats different kinds of shape objects in the same way, such as: Write a method that prints any shape's area and perimeter. Create an array of shapes that could hold a mixture of the various shape objects. Write a method that could return a rectangle, a circle, a triangle, or any other shape we've written.

44 Interfaces interface: A list of methods that a class can implement.
Inheritance gives you an is-a relationship and code-sharing. A Lawyer object can be treated as an Employee, and Lawyer inherits Employee's code. Interfaces give you an is-a relationship without code sharing. A Rectangle object can be treated as a Shape. Analogous to the idea of roles or certifications: "I'm certified as a CPA accountant. That means I know how to compute taxes, perform audits, and do consulting." "I'm certified as a Shape. That means I know how to compute my area and perimeter."

45 Declaring an interface
public interface name { public type name(type name, ..., type name); ... } Example: public interface Shape { public double area(); public double perimeter(); abstract method: A method header without an implementation. The actual body is not specified, to allow/force different classes to implement the behavior in its own way.

46 Implementing an interface
public class name implements interface { ... } Example: public class Bicycle implements Vehicle { A class can declare that it implements an interface. This means the class must contain each of the abstract methods in that interface. (Otherwise, it will not compile.) (What must be true about the Bicycle class for it to compile?)

47 Interface requirements
If a class claims to be a Shape but doesn't implement the area and perimeter methods, it will not compile. Example: public class Banana implements Shape { ... } The compiler error message: Banana.java:1: Banana is not abstract and does not override abstract method area() in Shape ^

48 Exercise

49 Interface Example public interface Shape { }
public abstract double area(); public abstract double perimeter(); }

50 Complete Circle class // Represents circles.
public class Circle implements Shape { private double radius; // Constructs a new circle with the given radius. public Circle(double radius) { this.radius = radius; } // Returns the area of this circle. public double area() { return Math.PI * radius * radius; // Returns the perimeter of this circle. public double perimeter() { return 2.0 * Math.PI * radius;

51 Complete Rectangle class
// Represents rectangles. public class Rectangle implements Shape { private double width; private double height; // Constructs a new rectangle with the given dimensions. public Rectangle(double width, double height) { this.width = width; this.height = height; } // Returns the area of this rectangle. public double area() { return width * height; // Returns the perimeter of this rectangle. public double perimeter() { return 2.0 * (width + height);

52 Complete Triangle class
// Represents triangles. public class Triangle implements Shape { private double a; private double b; private double c; // Constructs a new Triangle given side lengths. public Triangle(double a, double b, double c) { this.a = a; this.b = b; this.c = c; } // Returns this triangle's area using Heron's formula. public double area() { double s = (a + b + c) / 2.0; return Math.sqrt(s * (s - a) * (s - b) * (s - c)); // Returns the perimeter of this triangle. public double perimeter() { return a + b + c;

53 Interfaces + polymorphism
Interfaces don't benefit the class so much as the client. Interface's is-a relationship lets the client use polymorphism. public static void printInfo(Shape s) { System.out.println("The shape: " + s); System.out.println("area : " + s.area()); System.out.println("perim: " + s.perimeter()); } Any object that implements the interface may be passed. Circle circ = new Circle(12.0); Rectangle rect = new Rectangle(4, 7); Triangle tri = new Triangle(5, 12, 13); printInfo(circ); printInfo(tri); printInfo(rect); Shape[] shapes = {tri, circ, rect};

54 Summary What is an interface? What is an abstract method?
A list of methods that a class can promise to implement. An interface is a collection of abstract methods. What is an abstract method? A method header without an implementation. The actual body is not specified, to allow/force different classes to implement the behavior in its own way. What is required of a class implementing an interface? The class must contain each of the abstract methods in that interface. (Otherwise, it will not compile.) How do interfaces let client’s use polymorphism?

55 Abstract Classes An abstract class is one that cannot be instantiated.
You just cannot create an instance of the abstract class. If a class is abstract and cannot be instantiated, the class does not have much use unless it is subclassed. This is typically how abstract classes come about during the design phase. A parent class contains the common functionality of a collection of child classes, but the parent class itself is too abstract to be used on its own.

56 Abstract Classes Java Abstract classes are used to declare common characteristics of subclasses. An abstract class cannot be instantiated. It can only be used as a superclass for other classes that extend the abstract class. Abstract classes are declared with the abstract keyword. All other functionality of the class still exists, and its fields, methods, and constructors are all accessed in the same manner. Abstract classes are used to provide a template or design for concrete subclasses down the inheritance tree. We can also implement the generic shapes class as an abstract class so that we can draw lines, circles, triangles etc. All shapes have some common fields and methods, but each can, of course, add more fields and methods. The abstract class guarantees that each shape will have the same set of basic properties. We declare this class abstract because there is no such thing as a generic shape. There can only be concrete shapes such as squares, circles, triangles etc.

57 Declaring an abstract class
public abstract class name { public abstract type name(type name, ..., type name); ... } Example: public abstract class Shape { private String color; public abstract double area(); public abstract double perimeter(); public Shape(){ color = "Red"; public Shape(String color){ this.color = color; public String getFillColor(){ return color;

58 Abstract Classes vs Interfaces
Similarities You cannot instantiate them. Contain abstract methods Differences A class can only derive from one class, whereas a class can implement multiple interfaces Instance methods in an interface don’t require the abstract keyword, as they are implicitly abstract, whereas in an abstract class the abstract keyword is required for abstract methods. In abstract classes, you can declare fields that are not static and final. Abstract classes can contain non-abstract methods, whose implementation can be reused by subclasses.

59 Arraylist.. Most used and Flexible container classes in Java. What is container/collection object ?

60 Java collections framework

61 Deciding between Abstract Class or Interface
Consider using abstract classes if any of these statements apply to your situation: You want to share code among several closely related classes. You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private). You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong. Consider using interfaces if any of these statements apply to your situation: You expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes. You want to take advantage of multiple inheritance of type.

62 Summary What keyword do you use to designate a class is abstract?
Name two similarities of interfaces and abstract classes? They contain abstract methods You cannot instantiate them Name two differences of interfaces and abstract classes? A class can only derive from one class, whereas a class can implement multiple interfaces Instance methods in an interface don’t require the abstract keyword, as they are implicitly abstract, whereas in an abstract class the abstract keyword is required for abstract methods. In abstract classes, you can declare fields that are not static and final. Abstract classes can contain non-abstract methods, whose implementation can be reused by subclasses.

63 Unit Review

64 Topics Inheritance Object class Override Type casting objects
Superclass and subclass Object class Override Type casting objects Super keyword Polymorphism Interfaces Abstract Classes

65 Inheritance inheritance: A way to form new classes based on existing classes, taking on their attributes/behavior. a way to group related classes a way to share code between two or more classes One class can extend another, absorbing its data/behavior. superclass: The parent class that is being extended. subclass: The child class that extends the superclass and inherits its behavior. Subclass gets a copy of every field and method from superclass

66 Inheritance syntax By extending Car, each ElectricCar object now:
public class name extends superclass { Example: public class ElectricCar extends Car { ... } By extending Car, each ElectricCar object now: receives a xpos, ypos, direction, radioVolumeLevel, fuelState private fields and turn, drive, addFuel, changeRadioVolume, and getRadioVolume methods automatically can be treated as an Car by client code (seen later)

67 The Object Class The Object class sits at the top of the class hierarchy tree in the Java development environment. Every class in the Java system is a descendent (direct or indirect) of the Object class. The Object class defines the basic state and behavior that all objects must have, such as the ability to compare oneself to another object, to convert to a string, to wait on a condition variable, to notify other objects that a condition variable has changed, return the object's class.

68 Overriding methods override: To write a new version of a method in a subclass that replaces the superclass's version. No special syntax required to override a superclass method. Just write a new version of it in the subclass. public class ElectricCar extends Car { // overrides toString method in Car/Object class public String toString() { return “Electric: State of Charge: “ + charge; } ...

69 Type-casting objects Solution: Type-cast the object parameter to a Point. public boolean equals(Object o) { Point other = (Point) o; return x == other.x && y == other.y; } Casting objects is different than casting primitives. Really casting an Object reference into a Point reference. Doesn't actually change the object that was passed. Tells the compiler to assume that o refers to a Point object.

70 Calling overridden methods
Subclasses can call overridden methods with super super.method(parameters) Example: public class Tabby extends Cat { public String toString(){ return "Tabby"; } public String makeSound(){ return super.makeSound() + " and Meowww";

71 Calling superclass constructor
super(parameters); Example: public class Lawyer extends Employee { public Lawyer(int years) { super(years); // calls Employee constructor } ... The super call must be the first statement in the constructor. Exercise: Make a similar modification to the Marketer class.

72 Polymorphism polymorphism: Ability for the same code to be used with different types of objects and behave differently with each. System.out.println can print any type of object. Each one displays in its own way on the console. CritterMain can interact with any type of critter. Each one moves, fights, etc. in its own way.

73 Coding with polymorphism
A variable of type T can hold an object of any subclass of T. Animal skyWireFox= new Dog(); You can call any methods from the Animal class on skyWireFox. When a method is called on critter, it behaves as a Dog. System.out.println(skyWireFox); // Woof

74 Interfaces interface: A list of methods that a class can implement.
Inheritance gives you an is-a relationship and code-sharing. A Lawyer object can be treated as an Employee, and Lawyer inherits Employee's code. Interfaces give you an is-a relationship without code sharing. A Rectangle object can be treated as a Shape. Analogous to the idea of roles or certifications: "I'm certified as a CPA accountant. That means I know how to compute taxes, perform audits, and do consulting." "I'm certified as a Shape. That means I know how to compute my area and perimeter."

75 Declaring an interface
public interface name { public type name(type name, ..., type name); ... } Example: public interface Shape { public double area(); public double perimeter(); abstract method: A method header without an implementation. The actual body is not specified, to allow/force different classes to implement the behavior in its own way.

76 Abstract Classes Java Abstract classes are used to declare common characteristics of subclasses. An abstract class cannot be instantiated. It can only be used as a superclass for other classes that extend the abstract class. Abstract classes are declared with the abstract keyword. All other functionality of the class still exists, and its fields, methods, and constructors are all accessed in the same manner. Abstract classes are used to provide a template or design for concrete subclasses down the inheritance tree. We can also implement the generic shapes class as an abstract class so that we can draw lines, circles, triangles etc. All shapes have some common fields and methods, but each can, of course, add more fields and methods. The abstract class guarantees that each shape will have the same set of basic properties. We declare this class abstract because there is no such thing as a generic shape. There can only be concrete shapes such as squares, circles, triangles etc.

77 Declaring an abstract class
public abstract class name { public abstract type name(type name, ..., type name); ... } Example: public abstract class Shape { private String color; public abstract double area(); public abstract double perimeter(); public Shape(){ color = "Red"; public Shape(String color){ this.color = color; public String getFillColor(){ return color;

78

79

80 Problem #1 Statement Output Extra Credit Statements var1.method2();
In the table below, indicate in the right-hand column the output produced by the statement in the left-hand column. If the statement produces more than one line of output, indicate the line breaks with slashes as in "a/b/c" to indicate three lines of output with "a" followed by "b" followed by "c". If the statement causes an error, fill in the right-hand column with either the phrase "compiler error" or "runtime error" to indicate when the error would be detected. public class Neck extends Head { public void method2() { System.out.println("Neck 2"); } public class Head extends Arm { public void method1() { System.out.println("Head 1"); super.method2(); System.out.println("Head 2"); public class Leg { System.out.println("Leg 2"); public class Arm extends Leg { public void method3() { System.out.println("Arm 3"); method2(); And assuming the following variables have been defined: Arm var1 = new Neck(); Leg var2 = new Leg(); Leg var3 = new Arm(); Object var4 = new Head(); Arm var5 = new Head(); Head var6 = new Neck(); Statement Output Extra Credit Statements var1.method2(); ((Neck)var5).method1(); var2.method2(); ((Arm)var3).method3(); var3.method2(); ((Arm)var4).method1(); var4.method2(); ((Neck)var1).method1(); var5.method2(); ((Head)var4).method1(); var6.method2(); ((Arm)var2).method3(); var1.method3(); ((Head)var3).method1(); var2.method3(); ((Leg)var4).method2(); var3.method3(); var4.method3(); var5.method3(); var6.method3();

81 Problem #1 Answers Statement Output Extra Credit Statements
var1.method2(); Neck 2 ((Neck)var5).method1(); Runtime error var2.method2(); Leg 2 ((Arm)var3).method3(); Arm 3/Leg 2 var3.method2(); ((Arm)var4).method1(); Compile error var4.method2(); ((Neck)var1).method1(); Head 1/Leg 2 var5.method2(); Head 2 ((Head)var4).method1(); var6.method2(); ((Arm)var2).method3(); var1.method3(); Arm 3/Neck 2 ((Head)var3).method1(); var2.method3(); ((Leg)var4).method2(); var3.method3(); var4.method3(); var5.method3(); Arm 3/ Head 2 var6.method3();

82 Problem #2 public abstract class Bird { private String name;
private String noise; public Bird(String name, String noise){ this.name = name; this.noise = noise; } public String getName(){ return name; public String getNoise(){ return noise; public abstract String getFood(); An Owl is a Bird whose noise is “hoot”. The food it eats depends on the type of Owl, which means that getFood cannot be implemented in the Owl Class. Given the hierarchy shown above, write a complete class declaration for the class Owl, including its constructor and any method(s). 2. A SnowyOwl is an Owl whose name is always “Snowy Owl”. A SnowyOwl will randomly eat a hare, a lemming, or a small bird (depending on what’s available!), where each type is equally likely.. The SnowyOwl class should use a random number to determine which food the SnowyOwl will eat. Assuming that the Owl class has been correctly defined, and given the class hierarchy, write a complete declaration of the class SnowyOwl, including implementation of its constructor and method(s).


Download ppt "Unit 7 Textbook Chapter 9."

Similar presentations


Ads by Google