Java Lesson 05 – Inheritance

In this lesson we are going to continue with the classes from the last lesson. Do create a new project called Lesson 05.

Object instances

Look at the following code. What do you expect the System.out.println to print out? Now run the code. Where you wrong or correct? Why do you think that happened?

With the Animal b = a; you give b a reference to a, making both a and b point toward the same Object instance. So when you change a, b will also change.

Now look at the following code and try to guess what will happen again and try it out.

When a gets a new instance that doesnt mean b will also get a reference to that new instance. The b object will keep having the Miranda instnace that’s later renamed to Miranda.

Like I’ve said before all classes inherit the Object class this means any class can be cast to Object without any problems.

Inheritance

To make one class inherit another class you use the extends keyword. Now lets create a Horse class which inherits the Animal class. In this class also @Override the getType functions and directly return the correct type, so they dont have to be set anymore.

Now you should change the Animal class to an abstract class, because when you need Animal classes they should just create seperate classes for them.  You can also delete the setType function as that shouldnt be used anymore and change getType into a abstract function that should be overriden by classes that extend Animal. So far we used the toString() function to print out our animals, we are now going to create a print function in Animal instead.

An abstract function can not have any functionality so it doesn’t have curly brackets. Abstract can only be created in abstract classes and when a class inherits an abstract class it will be forced to create all abstract functions in that class otherwise it will give errors. Give it a try by creating a Cat class which extends the Animal class. Also give this class two new functions isClipped that returns a boolean and a setClipped which sets if the cat has been clipped. Also @Override the print function to print out whether or not the cat has been clipped.

Result SelectShow

Now if you create an instance of the Cat class and print it, it will show whether or not your cat has been clipped.

<h2>Assignment</h2>
Create two new functions in the Animal class called setAge and getAge. These functions will take an int. Also create an abstract function called getAverageAge with an int as return type. Next create some more animals and like the cat try and think of unique functions and variables to give them and override the getAverageAge and getType correctly in them.
<h2>Download</h2>
The examples and the solutions to the Assignment you can <a href=”https://dl.dropboxusercontent.com/u/3096920/tutorials/java/Lesson%2005.zip”>download here</a>