You are on page 1of 8

Modules: Print Module

Lesson 8 Inheritance.htm[27/03/2014 03:13:10 PM]


Send to Printer | Close Window

Lesson 8: Inheritance
Outcomes for this lesson
Copyright (c) 2014, Unisa
Outcomes

In this lesson, you will learn how to:

Demonstrate and explain UML (Unified Modeling Language) class diagrams
Use the extends keyword to inherit a class
Compare and contrast superclasses and subclasses
Explain how inheritance affects member access
Use super to call a superclass constructor
Use super to access superclass members
Create a multilevel class hierarchy
State when constructors are called in a class hierarchy
Apply superclass references to subclass objects

Purpose
As a programmer, you want to write clean, efficient code, and you want to avoid duplication wherever possible since clean, readable
code allows other programmers to easily understand your code.

Additionally, the more code you can reuse, the fewer bugs you encounter and the less time you spend re-writing already-exiting code.

You can think of reusing code through inheritance as being a lot like borrowing something you need from a friend.
You may not want to purchase an expensive piece of clothing or purchase a tool if you are only going to use it once.
To avoid spending more money (or time) than you need to, why not just borrow the item from a friend?
Inheriting code can save you the time and effort of writing it for yourself!

What is Inheritance?
Copyright (c) 2014, Unisa
What is Inheritance?
Inheritance is a simple but powerful tool of object oriented languages that allows classes to inherit methods and fields from other
classes.

Inherit: to receive or obtain something from your predecessor or parent
In J ava, the concept of inheritance is similar to genetics
Genes and genetic traits are passed down from parent to child
Children often look and act like their parents as a result.

Modules: Print Module
Lesson 8 Inheritance.htm[27/03/2014 03:13:10 PM]
How Does Inheritance Work in Java?
In J ava, inheritance works with parent and child classes:
Parent classes define a set of fields/variables and a set of methods
Also known as a superclass

Child classes are subsets of parent classes, and they let us use the methods and fields from their parents, which is referred to as
inheriting methods.
Also known as a subclass

Superclass vs. Subclass

Classes can derive from or evolve out of parent classes, which means they contain the same methods and fields as their parents, but
can be considered a more specialised form of their parent classes.
The difference between a subclass and a superclass is as follows:
SuperClass SubClass
The more general class from
which other classes derive
their methods and data
The more specific class that
derives or inherits from another
class (the superclass)
Superclasses contain methods and fields that are passed down to all of their subclasses.
Subclasses inherit methods and fields of their superclasses.
A subclass may have define additional methods or fields that the superclass does not have.
Example:
Study the structure below, then download from myUNISA the classes for School.
Modules: Print Module
Lesson 8 Inheritance.htm[27/03/2014 03:13:10 PM]
1) Start by viewing at the code for class Per son. This is the main class.
2) Now view at the code for class Empl oyee.
The class Empl oyee extends the class Per son.
All the methods in the class Per son are available to the class Empl oyee
3) Now view the code for the class Teacher .
The class Teacher extends the class Per son.
All the methods in the class Per son are available to the class Per son
4) Now view the code for the classes Per manent Teacher and Cont r act Teacher .
Both these classes extend the class Teacher .
All the methods in the class Per son and in the class Teacher are available to PermanentTeacher and Cont r act Teacher .
How to create a subclass that inherits the constructor (with parameters) from the parent (superclass):
Below are the steps that you can follow to create a superclass (parent class) and subclasses (children):
Create a new Android Application, name it MyShapes.
- One screen
- One TextView field where we will display the results
- In MainActivity.java Link the TextView field to the code.
Step 1: Create a class Shape with a public method Display.
publ i c cl ass Shape {
/ / i nst ance var i abl es
St r i ng shapeName;
/ / const r uct
publ i c Shape( St r i ng sName) {
t hi s. shapeName = sName;
}/ / Shape
/ / publ i c met hods

publ i c St r i ng Di spl ay( ) {
r et ur n " Shape: " + t hi s. shapeName;
}
Step 2: Create a class Rectangle (this class is going to be a subclass of Shape)
Create the class Rectangle, but do not include any code:
publ i c cl ass Rect angl e {
}
Modules: Print Module
Lesson 8 Inheritance.htm[27/03/2014 03:13:10 PM]
Step 3: add the code extends Shape:
public class Rectangle extends Shape {

}
Hover the mouse over Rectangle
Accept the 'Add constructor 'Rectangle(String)'
The default constructor is created and includes super ( sName) . This super extends the parameters from the superclass Shape.
Thus when an object of Rectangle is created, it MUST include a parameter that contains the name of the shape.
Now add the instance variables and methods for this class:
Below is an example of such code for this class:
publ i c cl ass Rect angl e ext ends Shape{
//instance variables
int length, width;
publ i c Rect angl e( St r i ng sName) {
super ( sName) ;
/ / TODO Aut o- gener at ed const r uct or st ub
this.length = len;
this.width = wid;
}
}
Hover the mouse over 'l en' and select Create Parameter 'len'. Do the same for 'wi d' .
Notice that these two parameters (len and wid) are now added as parameters to the constructor.

Thus, when an object of the class Rectangle is created, it MUST have parameters for the (1) name of the shape, (2) the length and
(3) the width.
Modules: Print Module
Lesson 8 Inheritance.htm[27/03/2014 03:13:10 PM]
Add some public and private methods. Your code should now be something like:
publ i c cl ass Rect angl e ext ends Shape{

/ / i nst ance var i abl es
i nt l engt h, wi dt h;
publ i c Rect angl e( St r i ng sName, int len, int wid) {
super ( sName) ;
/ / TODO Aut o- gener at ed const r uct or st ub
t hi s. l engt h = l en;
t hi s. wi dt h = wi d;
}

}
Step 4: Add methods to this class
Add methods to the class Rectangle, examples (1) to calculate the area (private method) and (2) display something (public method)
Notice in the code that the Di spl ay( ) method from the Shape class is used as well as the private method ar ea( ).
publ i c cl ass Rect angl e ext ends Shape{

/ / i nst ance var i abl es
i nt l engt h, wi dt h;
publ i c Rect angl e( St r i ng sName, i nt l en, i nt wi d) {
super ( sName) ;
/ / TODO Aut o- gener at ed const r uct or st ub
t hi s. l engt h = l en;
t hi s. wi dt h = wi d;
}

/ / pr i vat e met hods
private int area(){
return this.length * this.width;
}
/ / publ i c met hods

public String DisplayRectange(){
return Display() + " Area: " + area();
}
Modules: Print Module
Lesson 8 Inheritance.htm[27/03/2014 03:13:10 PM]

}
Step 5: Go back to MainActivity.java and create objects of the classes
publ i c cl ass Mai nAct i vi t y ext ends Act i vi t y {

@Over r i de
pr ot ect ed voi d onCr eat e( Bundl e savedI nst anceSt at e) {
super . onCr eat e( savedI nst anceSt at e) ;
set Cont ent Vi ew( R. l ayout . act i vi t y_mai n) ;

/ / l i nk t he wi dget s t o t he code

Text Vi ew f Di spl ay = ( Text Vi ew) f i ndVi ewByI d( R. i d. t xt Di spl ay) ;

St r i ng sDi spl ay = " " ; / / use t hi s var i abl e t o di spl ay i nf o on t he scr een

/ / my code

/ / cr eat e an obj ect of t he cl ass Shape.

Shape shape1 = new Shape( " Box" ) ;

/ / t he onl y publ i c met hod avai l abl e f or shape1 i s Di spl ay( )

sDi spl ay = sDi spl ay + " Shape 1: " + shape1. Di spl ay( ) + " \ n" ;

/ / cr eat e an obj ect of t he cl ass Rect angl e.

Rect angl e shape2 = new Rect angl e( " Ti l e" , 50, 40) ;

/ / t he publ i c met hod of Rect angl e
/ / as wel l as t he publ i c met hod of Shape i s avai l abl e

sDi spl ay = sDi spl ay + " Shape 2: " + shape2. Di spl ay( ) + " \ n" ;

sDi spl ay = sDi spl ay + " Shape 2: " + shape2. Di spl ayRect angl e( ) + " \ n" ;


}
@Over r i de
publ i c bool ean onCr eat eOpt i onsMenu( Menu menu) {
/ / I nf l at e t he menu; t hi s adds i t ems t o t he act i on bar i f i t i s pr esent .
get MenuI nf l at er ( ) . i nf l at e( R. menu. mai n, menu) ;
r et ur n t r ue;
}
}

Save, compile, debug and sort out all errors. Run the application.

If you really struggle, then download the code MyShapes from Additional Resources on myUNISA.


Assignment 1 - Task 9
Copyright (c) 2014, Unisa
Modules: Print Module
Lesson 8 Inheritance.htm[27/03/2014 03:13:10 PM]
Assignment 1 - Task 9
You should now be very near to the end of developing your application.
In this lesson we have learned more on inheritance between classes. Indicate in your project where you are going to implement
inheritance.
Indicate how you are going to apply it in your final project.
Edit the notes on the ideas for your project.
Include the following in your project:
- How will you link the pages (screens) - are you going to use buttons or lists.
- What is the purpose of each screen
- Do you need to create / download images?
- How can you optimize your code using classes, objects and arrays?
- Do I need to link with external webpages?
- What about splash screens. Are you going to use images from the internet? What about copyright issues?
- Are you going to include music / audio. What about copyright issues.
- How you are going to deal with user input. Catching errors. Think of errors that may occur where you are dealing with arrays as well
- Overloading of methods
- Inheritance between classes
Continue with the implementation and finalisation of your coding.
Remember you can update and change as we go along (but you may not change from your initial choice of app.)
Upload this document on DropBox.
Give it a proper version number, e.g. 12345678_dev_v8.docx. (Where 12345678 is your student number).
I am only going to mark the final document, BUT, I am going to refer back to the different versions. If you haven't worked during the
semester on your project, then you are not going to get good marks for the final document. Further, if you contact me to assist you,
then I am going to refer to your documentation as well.
Lesson 8: Summary
Copyright (c) 2014, Unisa
Lesson 8: Summary
Now it is your turn ...
In the blogger add a blog entry. Label it Lesson 8. In this blog, enter a short summary for yourself of everything that we've learned.
Specifically those components that you've battled with and how you solved it.
Remember to keep notes and updates in your little black book.
I am not going to mark it, but if you request of me to assist you then I will first of all look at your blogger. Your entries, when you've
Modules: Print Module
Lesson 8 Inheritance.htm[27/03/2014 03:13:10 PM]
made it, your comments etc.

You might also like