type name - Issaquah Connect

Download Report

Transcript type name - Issaquah Connect

Unit 6
Textbook Chapter 9
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.
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 doubleprecision argument, etc.).
• Covered next class
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
Inheritance syntax
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)
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.
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.
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;
}
...
}
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.
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");
}
p1
p2
x
5
y
3
5
y
3
...
x
...
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.
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;
}
}
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.
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?
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.
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
return x == o.x && y == o.y;
^
• The compiler is saying,
"o could be any object. Not every object has an x field."
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.
expression
result
s instanceof Point
false
s instanceof String
true
p instanceof Point
true
p instanceof String
String s = "hello";
Point p = new Point(); p instanceof Object
s instanceof Object
false
true
true
null instanceof String false
null instanceof Object false
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;
}
}
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
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
Vehicle
Car
Truck
Your Test Harness class with the static main method
Your generic primary super class
Your car class that inherits the vehicle class
Your truck class that inherits the vehicle class
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.
Learning Objectives
• Create a method that uses the super keyword.
• Develop a constructor that calls its superclass’s constructor.
• Differentiate between inheritance and polymorphism.
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.
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";
}
}
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)
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 nonexistent default Animal constructor.
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.
Polymorphism
• Why use it?
• Create extensible programs
• So that your program can more easily handle future changes
• Possibly, reduce the quantity of required code
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.
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
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();
Teacher steve = new Teacher();
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.0
v.days: 15
v.form: pink
salary: 50000.0
v.days: 10
v.form: yellow
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:
salary:
v.days:
salary:
v.days:
salary:
v.days:
50000.0
15
50000.0
10
60000.0
10
55000.0
10
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.
•
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();
}
Polymorphism answer
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
baz
baz 1
mumble 2
foo
foo 1
foo 2
Diagramming the classes
• Add classes from top (superclass) to bottom (subclass).
• Include all inherited methods.
Finding output with tables
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
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.
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.
INTERFACES
Relatedness of types
Write a set of Circle, Rectangle, and Triangle classes.
• Certain operations that are common to all shapes.
perimeter
area
- distance around the outside of the shape
- amount of 2D space occupied by the shape
• Every shape has them but computes them differently.
Shape area, perimeter
• Rectangle (as defined by width w and height h):
area
perimeter
=wh
= 2w + 2h
• Circle (as defined by radius r):
area
perimeter
=  r2
=2r
• Triangle (as defined by side lengths a, b, and c)
area
perimeter
= √(s (s - a) (s - b) (s - c))
where s = ½ (a + b + c)
=a+b+c
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.
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."
Declaring an interface
public 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.
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?)
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
public class Banana implements Shape {
^
EXERCISE
Interface Example
public interface Shape {
public abstract double area();
public abstract double perimeter();
}
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;
}
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);
}
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;
}
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};
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?
• Interface's is-a relationship lets the client use polymorphism.
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.
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.
Declaring an abstract class
public 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;
}
}
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.
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.
Arraylist..
Java collections framework
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.
UNIT REVIEW
Topics
1. Inheritance
1.
2.
3.
4.
5.
6.
7.
8.
Superclass and subclass
Object class
Overriding methods
Type casting objects
Super keyword
Polymorphism
Interfaces
Abstract Classes
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
Inheritance syntax
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)
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.
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;
}
...
}
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.
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";
}
}
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.
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.
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
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."
Declaring an interface
public 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.
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.
Declaring an abstract class
public 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;
}
}
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();
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();
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
Problem #2
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).
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();
}
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).
Problem #3
• Consider the following partial declaration of class
BirdSanctuary