week111 apcs-ab: java inheritance november 17, 2005

51
week11 1 APCS-AB: Java Inheritance November 17, 2005

Upload: alyson-davidson

Post on 04-Jan-2016

221 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 1

APCS-AB: Java

Inheritance

November 17, 2005

Page 2: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 2

Checkpoint

• Design Project - from Henry and Eric

• USB drives (and check-out form to be signed by parents)

Page 3: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 3

Nested classes

• A class can be declared inside another class• The nested class is a member of the enclosing class, so it can use

the enclosing class’s instance variables & methods, even if they are private

• But enclosing class can only use data in the nested class if the data is public (In this case, it is okay to have data public, because only the enclosing

class would be able to see it)• A class should only be nested inside another if it makes sense by the

design of the objects• The static modifier can be applied to a nested class• A nonstatic nested class is called an inner class

An inner class is associated with each instance of the enclosing class

Page 4: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 4

Making a Zoo

• If we wanted to model a zoo, what kind of objects would we need?

• What would those objects do? (i.e. what are the instance variables?)

• What would those objects know? (i.e. what are the methods?)

Page 5: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 5

Our zoo

• In order to not duplicate lots of information that is shared by our data, could be maybe set up a hierarchy of objects similar to the Taxonomy that we’ve learned about in Biology class?

Animal

Mammal Reptile

CaninePrimate

Dog Wolf

Page 6: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 6

Of course we can… we just need some Inheritance

Page 7: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 7

Inheritance

• Inheritance allows us to do just that ! We can describe higher level objects (like Animal or

Mammal) and have characteristics (or actions) defined there that are true for any object beneath it in the hierarchy

This saves us from repeating tons of code!

• The high level class is the parent class (aka superclass or base class)

• The derived (lower level) classes is the child class (aka subclass)

Page 8: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 8

Inheritance

• Form of software reuse in which classes are created by absorbing an existing class’s data and methods and then you can embellish them with new or

modified capabilities

• Allows you to define a very general class and later define more specialized classes by adding new details

Page 9: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 9

So you have a hierarchical relationship -- now what??

• You must define the Superclass:public class Animal{String name;int size;public void eat(){ //do something }

}

• Then you define the the Subclass, which needs to extend the Superclass (using the Java keyword extends). The subclass has everything in the superclass, plus anything else you want to add!

public class Dog extends Animal{public void bark(){ //do something }

}

Note: if fido is an object of type Dog, you can call fido.eat() and java will recognize the method as valid

Page 10: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 10

IS-A Relationship

• Inheritance is always an IS-A relationship To make sure you are designing your classes

properly and making use of inheritance, ask yourself:

• Does SubClass IS-A Superclass make sense?• Does Dog IS-A Animal make sense?• Does Janitor IS-A Employee make sense?• Does Triangle IS-A ThreeDimensionalShape make

sense?

Page 11: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 11

Designing with Inheritance

• Make sure you think out the relationships between all the objects and what makes sense

• Practice Abstraction Focus on the big picture and commonalities between

objects, rather than on implementation details

Page 12: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 12

Another Sample Hierarchy

Shape

TwoDimensionalShape ThreeDimensionalShape

Triangle SquareCircle TetrahedronCubeSphere

Page 13: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 13

Book Example (From Ch 8)

Book• protected int pages = 1500;• setPages(int numPages)• int getPages()

Dictionary (is-a Book)• int definitions = 52500;• Double computRatio()• setDefintions(int numDefinitions)• getDefintions()

public class Words{Dictionary webster = new Dictionary();webster.getPages();webster.getDefinitions();webster.computeRatio();

}

Page 14: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 14

How it works

• The Book code is needed to create the definition of Dictionary, but we never need a Book object

• Inheritance is a one-way street Dictionary can use methods/variables of Book,

but not the other way around

Page 15: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 15

What is the protected qualifier?

• The protected keyword is the best encapsulation that still permits inheritance If a superclass declares its data or methods protected

it means that any subclasses can access the data• It also means that any thing in that package can also access

the data

• Private superclass members can only be changed by a subclass by using non-private accessor methods

Page 16: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 16

Methods in the Superclass

• The Superclass can define methods and indicate data that all the Subclasses should have

• But what if the subclass wants to behave differently than the superclass It can override the superclass’s method Overriding is kind of like overloading

• What do you think the difference is?

Page 17: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 17

Overloading

public class myClass{public myClass(){

} public myClass(int x, int y){

}

public void move(){ } public void move(int x){

}}

Overloading =Two methods with the same name,

But different method signatures

Page 18: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 18

Overriding

• Superclass has a method:public void rotate(){System.out.println(“Spin Right”);

}

• Subclass wants to redefine method:public void rotate(){

System.out.println(“Spin Left”); }

Overriding = Method with the same name But different functionality in a

superClass and subClass

Page 19: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 19

Overriding

• We’ve already been using Overriding! Every class in Java extends from java.lang.Object This class defines a toString method (which by default

returns the internal representation of the object) When we make our toString methods, we override the

default version and return something more meaningful

• What do we do if we want to use part of the superclass’s method (or part of its constructor)? Use the super reference

Page 20: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 20

The super reference

• The super reference refers to an object’s direct superclass (one level up in the hierarchy tree)

• super() refers to the Superclass’s constructor• super.doStuff() would refer to the Superclass’s

doStuff method• super.x would refer to the Superclass’s variable

named x (assuming a protected variable)

Page 21: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 21

Constructors in inheritance

• Constructors are not inherited from the superclass at all.

• If you want to access the superclass constructors, you must use super()

Page 22: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 22

A little example

class Animal {String name;String noise;public Animal(String name, String noise){this.name = name;this.noise = noise;

}public void movement (){

System.out.println(“Moving”);}

}

Page 23: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 23

A little example

class Dog extends Animal {int mySize;public Dog(String name, String noise, int size){

super(name,noise);mySize = size;

}public Dog(){

super(“Fido”, “Woof”);}public void movement (){

System.out.println(“Walking”);}

}

Page 24: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 24

Sudoku

• How’s it working? Any questions?

• Due Friday…

Page 25: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 25

APCS-AB: Java

Polymorphism, Abstract and Interfaces

November 18, 2005

Page 26: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 26

Polymorphism

• If we say that every class in Java extends (inherits) from Object, that means that everything IS-A Object.

• Inheritance allows us to use the more general category to refer to all the subclasses. Use the generic superclass Animal to refer to all the

different animal subclasses • This allows you to have really flexible code

Its cleaner, more efficient, easier to develop & easier to extend!

Page 27: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 27

In the world before inheritance

• We declared a reference variable Dog myDog;

• We created the object and assigned it to the reference myDog = new Dog(); Or in one step: Dog myDog = new Dog();

• And the reference type and the object were the same (they were both Dogs)

Page 28: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 28

Now…

• With polymorphism, the reference type and the object type can be different

• Animal myDog = new Dog();

• The reference type can be a superclass of the actual object type.

Page 29: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 29

Some code

Animal [] animals = new Animal[5];animals[0] = new Dog();animals[1] = new Cat();animals[2] = new Wolf();animals[3] = new Hippo();animals[4] = new Lion();for(int i=0; i<animals.length; i++){animals[i].eat();animals[i].move();

}

Page 30: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 30

What it does

animals[i].eat();animals[i].move();

• When i is 0, we have a Dog and the Dog’s eat() method is called, but when i is 1, we have a Cat and the Cat’s eat method is called

• This works for any of the Animal-class methods

• The process of deciding which method (i.e. from which object) to use at run time is called dynamic (or late) binding

Page 31: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 31

What it means

• Write code using polymorphic arguments, declare the method parameter as a superclass type – then you can pass in any subclass object at runtime So you can write your code, pass it off to

someone else, and they can add all the new subclass types – your methods will still work

Page 32: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 32

Rules for overriding

• When you override a method, you are agreeing to fulfill the contract (the method specification) Return type and parameters (number and

type) need to be exactly the same as the overridden method in the superclass

The method can’t be less accessible (but it can be more)

• So the subclass method can’t be private if the superclass method was public

Page 33: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 33

Polymorphism in action

• The Java Library is bursting with polymorphism Tons of methods with generic and abstract

arguments and return types Collections, classes, & methods in the library

work with all the classes you create (classes that the creators of Java had no idea you were going to write!)

• Because everything is an Object (there is an implicit extension)

Page 34: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 34

What’s in Object class?

• “Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.”

• The mega superclass has: boolean equals() Class getClass() int hashCode() String toString() Object clone() And more…

Page 35: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 35

Abstract

Page 36: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 36

Abstract Classes

• Classes that can’t be instantiated• Animal class is good for inheritance and polymorphism,

but we can’t really have a generic Animal object So restrict it by declaring it an abstract class Inheritance still works, so the subclasses still benefit from the

Animal definition, we’re just enforcing the fact that you can’t create an object of type Animal

Page 37: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 37

Concrete Classes

• When you are designing inheritance structure – some classes are specific enough to be instantiated These are the concrete ones

Page 38: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 38

Abstract Methods

• If a method must be overriden – make it abstract You’ll get a compile time error if you don’t write the method in the

subclass

• An abstract method has no body, it exists only for polymorphism The first concrete class in the inheritance tree must implement all

abstract methods

• An abstract method has to be in an abstract class (but that class can contain non-abstract methods as well)

Page 39: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 39

Interfaces

Page 40: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 40

Interfaces

• An Interface is a 100% abstract class, it can’t be instantiated

• Another way to take advantage of polymorphism – another contract that objects can fulfill

• Let’s explore this a little more to see why it is necessary

Page 41: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 41

Two superclasses?• Why do you think we have interfaces instead of having the base

class extend two superclasses? (Why can multiple inheritance be a bad thing?)

Digital Recorder

burn()

CDBurner

burn()

DVDBurner

burn()

ComboDrive

Page 42: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 42

Multiple Inheritance

• Leads to ambiguity “The Deadly Diamond of Death” In our example: which burn method would

ComboDrive inherit?

• Don’t want the language to have to support/encode special rules to deal with ambiguity

• Ambiguity is bad in programming!

Page 43: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 43

And therefore

• Java has interfaces instead of multiple inheritance• Gives you the benefits of multiple inheritance without

ever putting you in the situation of the Deadly Diamond of Death

• All methods in an interface are abstract Nothing is inherited, the subclass must implement the methods

and the JVM will never get confused about which version of an inherited method it was supposed to call

Page 44: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 44

Another interface benefit

• You can now have classes from different inheritance trees implement the same interface

Animal

Canine

Dog LionCat

Feline

Wolf

Robot

RoboDogAgent

Pet

Page 45: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 45

Interfaces in JavaAPI

• Comparable• Iterator• List• Collection• EventListener• ErrorHandler

• And on and on and on (They’re listed in italics in the API docs)

Page 46: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 46

Exercise – Draw it!

public class Gamma extends Delta implements Epsilon{}

public interface Epsilon{}

public interface Beta {}

public class Alpha extends Gamma implements Beta {}

public class Delta {}

Page 47: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 47

Other Stuff

Page 48: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 48

null and this references

• null Represents a reference that does not point to a valid object So we can use null for objects that do not exist, but not primitives

• this The way for an object to reference itself In a method, it can be used to refer to instance variables and

other methods in the object

Page 49: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 49

Aliases

• Having multiple names for the same object in memoryCar car1 = new Car(“Audi”);Car car2 = new Car(“Ford”);car2 = car1;

• All references to the object that was originally references by car2 are now gone – oops no more Ford!

• Both car1 and car2 point to the same object!

• == operator compares the references and sees if they are aliases of each other

Page 50: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 50

Wrapper Classes

• Remember primitive data types are not objects But maybe you want the primitive as an equivalent object

• Java provides wrapper classes for all primitives Integer, Float, Double, Character, LongInteger n = new Integer(42);int i = n.intValue(); These classes also have useful constants & static methodsInteger.MAX_VALUE Integer.MIN_VALUE Integer.parseInt(“42”);//returns an int

Page 51: Week111 APCS-AB: Java Inheritance November 17, 2005

week11 51

Checkpoint

• Sudoku Where are you with it? Do you need more time?

• This weekend Study: Note - inheritance stuff is in Chapters 8 & 9 (although like

all the chapters in the book, we haven’t done everything in those chapters

(I’ll try to catch up on grading!)

• Monday - a little inheritance lab of some sort• Test on Tuesday