- Firstly, create and compile a
simple class called Parent. Give it the following behaviour:
- A default constructor that
does nothing other than print out “Parent default constructor” using System.out
- A single method called getMessage which returns a String, e.g.
“Parent message”
- Next, create and compile a
class called Child. Give it the following behaviour
- Do not give it a constructor
- Override the parent’s getMessage method to return an
alternative String. E.g. “Child message”
- A main method which creates an
instance of the Child object, and then writes the value returned by its getMessage method to the command line.
- What happens when the class is
run?
- Alter the Child class to give
it a default constructor which prints out “Child default constructor”.
Compile and run the application again and identify what happens.
- Alter the implementation of the
getMessage method in the Child class so that it
first calls the parent class method, then concatenates the result with its
own value to build a combined message. E.g. returning “Parent message and
Child message”.
- Alter the Parent class by
- Adding a new constructor that
accepts a String argument. This should be used to initialise a private
member variable, myMessage. Again write a message to the
console that indicates that the constructor has been called.
- Alter the getMessage method so that it returns the
value of the myMessage rather than a fixed message.
- Now alter the Child class so
that it from its default constructor it calls the new constructor on the
parent class.
- Alter the myMessage member variable in the Parent
class so that it is declared to be protected. Confirm that the Child class
can now refer to the variable directly, rather than having to call its
parent’s version of getMessage to build the combined message.
Can you think of the pros and cons of the two different mechanisms?
Sunday, 17 March 2013
Lab 3 July 2013 - Additional Exercise 3
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment