SubclassesCompositionComposition vs. InheritanceInheritanceAssignmentAssignment IIAssignment IIIArrays of ObjectsWrappersWrapper constructorsMore wrapper constructorsWrapper “deconstructors”Additional wrapper methodsBack to arraysTypes and valuesSending messagesOverriding methodsOverriding methods IISome methods cannot be overriddenSome variables cannot be shadowedSome classes cannot be extendedSome classes cannot be instantiatedSome objects cannot be alteredRule 70Rule 70, IIRule 70, IIIRelated style rules, IRelated style rules, IIRelated style rules, IIIRelated style rules, IVThe EndJan 13, 2019Subclasses2CompositionThe most common way to use one class within another is composition—just have a variable of that typeExamples:class LunarLanderGame { LunarLander lander = new LunarLander(); ...class MaxPlayer { String name; // String is a class Game game; // Game is a classComposition is suitable when one class is composed of objects from another class, or needs frequent reference to objects of another class3Composition vs. InheritanceInheritance is appropriate when one class is a special case of another classExample 1:class Animal { ... }class Dog extends Animal { ... }class Cat extends Animal { ... }Example 2:class Player { ... }class MaxPlayer extends Player { ... }class MinPlayer extends Player { ... }Use inheritance only when one class clearly specializes another class (and should have all the features of that superclass)Use composition in all other cases4Inheritanceclass Animal {int row, column; // will be inheritedprivate Model model; // private prevents inheritanceAnimal( ) { ... } // cannot be inheritedvoid move(int direction) { ... } // will be inherited}class Rabbit extends Animal {// inherits row, column, move, but not model or constructorint distanceToEdge; // new variable, not inheritedint hideBehindBush( ) { ... } // new method, not inherited}5AssignmentA member of a subclass is a member of the original class; a rabbit is an animal Animal animalBehindBush;Rabbit myRabbit;...animalBehindBush = myRabbit; // perfectly legal myRabbit = animalBehindBush; // not legal myRabbit = (Rabbit)animalBehindBush;// legal syntax, but requires a runtime check6Assignment II animalBehindBush = myRabbit; is legal—but why? int NUMBER_OR_ANIMALS = 8;Animal animals[ ] = new Animal[NUMBER_OR_ANIMALS];animals[0] = new Fox();animals[1] = new Rabbit();animals[2] = new Deer();... for (int i = 0; i < NUMBER_OR_ANIMALS; i++) animals[i].allowMove(); // legal if defined in Animal7Assignment IIIFrom previous slide:for (int i = 0; i < NUMBER_OR_ANIMALS; i++) allowMove(animals[i]); // legal if defined in AnimalBut:for (int i = 0; i < NUMBER_OR_ANIMALS; i++) { if (animals[i] instanceof Rabbit) { ((Rabbit)animals[i]).tryToHide(); }}Here, tryToHide() is defined only for rabbitsWe must check whether animals[i] is a rabbitWe must cast animals[i] to Rabbit before Java will allow us to call a method that does not apply to all Animals8Arrays of ObjectsWhen you declare an array, you must specify the type of its elements: Animal animals[ ];However, Object is a type, so you can say: Object things[ ]; // declaration things = new Object[100]; // definitionYou can put any Object in this array: things[0] = new Fox();But you cannot do this: things[1] = 5; // why not?9WrappersEach kind of primitive has a corresponding wrapper (or envelope) object:byte Byteshort Shortint Integer (not Int)long Longchar Character (not Char)boolean Booleanfloat Floatdouble Double10Wrapper constructorsEach kind of wrapper has at least one constructor:byte byteWrapper = new Byte(byte value)short shortWrapper = new Short(short value)int intWrapper = new Integer(int value)long longWrapper = new Long(long value)char charWrapper = new Character(char value )boolean booleanWrapper = new Boolean(boolean v a l u e)float floatWrapper = new Float(float va l ue)double doubleWrapper = new Double(double value)11More wrapper constructorsEvery wrapper type except Character has a constructor that takes a String as an argumentExample: Boolean b = new Boolean("true");Example: Integer n = new Integer("8702");These constructors for the numeric types can throw a NumberFormatException:Example: Integer i = new Integer("Hello");12Wrapper “deconstructors”You can retrieve the values from wrapper objects:byte by = byteWrapper.byteValue();short s = shortWrapper.shortValue();int i = intWrapper.intValue();long l = longWrapper.longValue();char c = charWrapper.charValue();boolean bo = booleanWrapper.booleanValue();float f = floatWrapper.floatValue();double d = doubleWrapper.doubleValue();13Additional wrapper methodsWrapper classes have other interesting featuresvariables:Integer.MAX_VALUE = 2147483647methods:Integer.toHexString(number)anyType.toString();14Back to arraysWhy bother with wrappers?Object[ ] things = new Object[100];You cannot do this: things[1] = 5;But you can do this: things[1] = new Integer(5);You cannot do this: int number = things[1];But you can do this: int number = ((Integer)things[1]).intValue();15Types and valuesA variable has both a type and a valueConsider Animal animal;The type of variable animal is AnimalThe type of a variable never changesThe syntax checker can only know about the typeThe value of animal might sometimes be a rabbit and at other times be a foxMessages such as animal.run() are sent to the valueThe value (object) determines which method to use16Sending messagesJava must ensure that every message is legalThat is, the object receiving the message must have a corresponding methodBut when the Java compiler checks syntax, it can’t know what the value of a variable will be; it has to depend on the type of the variableIf the variable is of type T, then eitherClass T must define an appropriate method, orClass T must inherit an appropriate method from a superclass, orClass T must implement an interface that declares an appropriate method17Overriding methodsclass Animal {int decideMove( ) {return Model.STAY;}}class Rabbit extends Animal {// override decideMoveint decideMove( ) { // same signature return random(Model.MIN_DIRECTION, Model.MAX_DIRECTION);}}18Overriding methods IIWhen you
View Full Document