CREATING REFERENCES AND OBJECTS

advertisement
Lesson 5: Worksheet 1
References, Objects, Polymorphism
Name___________________________
A. REVIEW CODE USED TO CREATE AN OBJECT
Syntax: Class reference = new Class(parameters);
B. 2 WAYS TO CREATE AN OBJECT
Type
Default
Polymorphism
Example
UrRobot karel = new UrRobot(1,1,North,0);
UrRobot karel = new MileWalker(1,1,North,0);
Description
same type: UrRobot on both sides
Parent class on left, child on right
C. WHAT HAPPENS WHEN YOU CREATE AN OBJECT
REFERENCE CLASS/TYPE
Example:
UrRobot
karel
OBJECT CLASS/TYPE
=
new UrRobot(1,1,North,0);
move,turnLeft,pickBeeper
putBeeper, turnOff
This side of code creates a
Reference or “Remote Control”
that refers to the object. The class
used here determines what commands
are available to use (on the remote).
This side of code creates the object.
The class used here determines the version
of the method to use. Java 1ST looks to see if the
method is defined in this object’s class. If not,
it moves up the inheritance tree to find a definition.
D. Complete Questions 1-3 using the Animal Inheritance Tree
Use this code to answer questions
Animal
makeNoise
eat
sleep
roam
Dog d = new Dog();
1. What type of reference (d) was created ?
Default or Polymorphism
Canine
Cat
makeNoise
eat
roam
Dog
makeNoise
eat
*** Note: If parent class and child class list the
same method, it means child class has overridden
parent version.
2. What methods/buttons does remote (d) have?
(remember a child inherits from the parent)
3. Which class will the object use to run method?
(remember: lowest in tree is always used!!!)
d.makeNoise();
Dog
Canine
Animal
d.roam();
Dog
Canine
Animal
d.eat();
Dog
Canine
Animal
d.sleep();
Dog
Canine
Animal
L5 Worksheet 1 cont’d…
Page 2
Using the diagram at the right, which of the following
will compile? If no, state why.
ANIMAL BOTS TREE
UrRobot
Note: You can't create object using abstract class.
AnimalBot(Abstract)
Example
UrRobot r = new UrRobot(…);
r.talk();
abstract talk()
No.
UrRobot has no talk method
Remember, the left side of this code determines the available methods.
In this case, UrRobot is on the left side which does not come with a
talk method.
1. DogBot r = new DogBot(…);
r.talk();
DogBot
move()
talk()
run()
dig()
CatBot
2. AnimalBot r = new DogBot(…);
r.talk();
run()
talk()
scratch()
3. AnimalBot r = new CatBot(…);
r.run();
4. AnimalBot r = new AnimalBot(…);
r.talk();
5. CatBot r = new CatBot(…);
r.scratch();
6. UrRobot r = new DogBot(…);
r.move();
7. UrRobot r = new DogBot(…);
r.talk();
8. Which questions 1-7 contain code which is both legal (compiles)
and exhibits Polymorphism. Hint: there are 2
HINT:
Did you find an
error with 3 of the
problems?
Download