82
Unit 7 Textbook Chapter 9

Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

Embed Size (px)

Citation preview

Page 1: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

Unit 7Textbook Chapter 9

Page 2: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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.

Page 3: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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

Page 4: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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

Page 5: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

Inheritance syntaxpublic 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)

Page 6: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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.

Page 7: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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.

Page 8: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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

Page 9: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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.

Page 10: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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 3p1

p2

...

x 5 y 3

Page 11: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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.

Page 12: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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

Page 13: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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 allowedPoint p = new Point(7, 2);if (p.equals("hello")) { // false ...

• equals should always return false if a non-Point is passed.

Page 14: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

equals and Objectpublic 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?

Page 15: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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.

Page 16: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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 symbolsymbol : variable xlocation: class java.lang.Objectreturn x == o.x && y == o.y; ^

• The compiler is saying,"o could be any object. Not every object has an x field."

Page 17: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

The instanceof keyword

if (variable instanceof type) { statement(s);

}

• Asks if a variable refersto 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 true

p instanceof String false

p instanceof Object true

s instanceof Object true

null instanceof String

false

null instanceof Object

false

Page 18: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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

Page 19: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

Summary• 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.• How do you compare two objects?• equals method

• How do you determine the type of an object?• instanceof method

Page 20: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

Inheritance – ExerciseBackground• 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

Page 21: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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.

Page 22: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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

Page 23: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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.

Page 24: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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

}}

Page 25: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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)

Page 26: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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.

Page 27: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

Calling superclass constructorsuper(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.

Page 28: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

Polymorphism• Why use it?• Create extensible programs

• So that your program can more easily handle future changes • Possibly, reduce the quantity of required code

Page 29: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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.

Page 30: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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

Page 31: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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: 50000.0salary: 50000.0v.days: 15 v.days: 10v.form: pink v.form: yellow

Page 32: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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: 50000.0v.days: 15salary: 50000.0v.days: 10salary: 60000.0v.days: 10salary: 55000.0v.days: 10

Page 33: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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.

Page 34: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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 { public void method2() { System.out.println("bar 2"); }}public class Baz extends Foo { public void method1() { System.out.println("baz 1"); } public String toString() { return "baz"; }}public class Mumble extends Baz { public void method2() { 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();}

Page 35: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

Polymorphism answerFoo[] 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:bazbaz 1foo 2foofoo 1bar 2bazbaz 1mumble 2foofoo 1foo 2

Page 36: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

• Add classes from top (superclass) to bottom (subclass).

• Include all inherited methods.

Diagramming the classes

Page 37: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

Finding output with tablesmethod Foo Bar Baz Mumble

method1

method2

toString

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 foo 1 baz 1 baz 1

method2 foo 2 bar 2 foo 2 mumble 2

toString foo foo baz baz

Page 38: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

Summary• What keyword do you use to call methods in the superclass?• super• 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.

Page 39: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

Review• 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 is polymorphism?• Ability for the same code to be used with different types of

objects and behave differently with each.

Page 40: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

INTERFACES

Page 41: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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 shapearea - amount of 2D space occupied by the shape

• Every shape has them but computes them differently.

Page 42: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

Shape area, perimeter• Rectangle (as defined by width w and height h):

area = w hperimeter = 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

Page 43: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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.

Page 44: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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, andLawyer 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 howto compute taxes, perform audits, and do consulting."

• "I'm certified as a Shape. That means I know howto compute my area and perimeter."

Page 45: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

Declaring an interfacepublic interface name { public type name(type name, ..., type 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.

Page 46: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

Implementing an interfacepublic 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?)

Page 47: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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 Shapepublic class Banana implements Shape {

^

Page 48: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

EXERCISE

Page 49: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

Interface Examplepublic interface Shape {

public abstract double area();public abstract double perimeter();

}

Page 50: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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

Page 51: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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

Page 52: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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

Page 53: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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

Page 54: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

Summary• What is an interface?• 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?•

Page 55: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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.

Page 56: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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.

Page 57: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

Declaring an abstract classpublic abstract class name { public abstract type name(type name, ..., type 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;

}

}

Page 58: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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.

Page 59: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

Arraylist..

Page 60: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

Java collections framework

Page 61: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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.

Page 62: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

Summary• What keyword do you use to designate a class is abstract?• 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.

Page 63: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

UNIT REVIEW

Page 64: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

Topics• Inheritance• Superclass and subclass

• Object class• Override• Type casting objects• Super keyword• Polymorphism• Interfaces• Abstract Classes

Page 65: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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

Page 66: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

Inheritance syntaxpublic 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)

Page 67: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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.

Page 68: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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

Page 69: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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.

Page 70: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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

}}

Page 71: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

Calling superclass constructorsuper(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.

Page 72: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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.

Page 73: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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

Page 74: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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, andLawyer 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 howto compute taxes, perform audits, and do consulting."

• "I'm certified as a Shape. That means I know howto compute my area and perimeter."

Page 75: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

Declaring an interfacepublic interface name { public type name(type name, ..., type 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.

Page 76: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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.

Page 77: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

Declaring an abstract classpublic abstract class name { public abstract type name(type name, ..., type 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;

}

}

Page 78: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs
Page 79: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs
Page 80: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

Problem #1 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(); } public void method2() { System.out.println("Head 2"); } } public class Leg { public void method2() { 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();

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.

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

Page 81: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

Problem #1 AnswersStatement 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(); Leg 2 ((Arm)var4).method1(); Compile error

var4.method2(); Compile error ((Neck)var1).method1(); Head 1/Leg 2

var5.method2(); Head 2 ((Head)var4).method1(); Head 1/Leg 2

var6.method2(); Neck 2 ((Arm)var2).method3(); Runtime error

var1.method3(); Arm 3/Neck 2 ((Head)var3).method1(); Runtime error

var2.method3(); Compile error ((Leg)var4).method2(); Head 2

var3.method3(); Compile error

var4.method3(); Compile error

var5.method3(); Arm 3/ Head 2

var6.method3(); Arm 3/Neck 2

Page 82: Unit 7 Textbook Chapter 9. The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs

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

}

1. 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).