程序代写代做代考 C Excel compiler Java FIT9131 Week 12

FIT9131 Week 12
Programming Foundations FIT9131
1
Inheritance Week 12

FIT9131 Week 12
Reminder : Assignment 2
Assignment 2 is due this Friday 12 June, at 10pm. Late submissions will incur heavy penalties, with no exceptions.
Submission Link will be available early this week.
Check FIT9131 Moodle site for more information on the submission requirements (in particular, the submission checklist).
2

FIT9131 Week 12
Lecture outline
• Inheritance
• Superclass/subclass relationship
• Protected access
• Static and dynamic types
• Overriding
• Polymorphism (variables, method calls) • Method lookup
• Subtyping
• Substitution
3

FIT9131 Week 12
Exam topics : Inheritance
• there will be no coding questions in the exam involving inheritance.
• there will be small theory questions, which require some general understanding of inheritance.
4

FIT9131 Week 12
Example : the Network project
We will use the “Network” sample Project in Chapter10 from the textbook to demonstrate some basic inheritance concepts. This project demonstrates :
➢a small, prototype social network ➢provides a simple news feed with posts ➢stores message (text) posts and photo posts
• MessagePost: multi-line text message
• PhotoPost: photo and caption ➢allows simple operations on the posts:
• eg. search, display and remove 5

FIT9131 Week 12
Main Classes for the Network project
filename
Note : in this implementation, only the file’s name is stored, not the actual image
attributes (fields)
6
behaviour (methods)

FIT9131 Week 12
Network Object model
7
Each object represents a single post; the object stores details for that particular post. Note : 2 different types of posts (message/photo)

FIT9131 Week 12
BlueJ
Class diagram
8

FIT9131 Week 12
Network Object relations
NewsFeed
PhotoPosts
MessagePosts
A NewsFeed object will hold two collections: one for MessagePosts, one for PhotoPosts These are (internally) implemented using 2 ArrayLists.
9

FIT9131 Week 12
Class design issue?
• this design, involving 2 separate kinds of “post” objects, seem quite reasonable at first sight, and is quite easy to implement…
• so what is the problem? ➢let’s examine the code…
10

FIT9131 Week 12
public class MessagePost
{
private String username;
private String message;
private long timestamp;
private int likes;
private ArrayList comments;
public MessagePost(String author, String text)
{
username = author;
message = text;
timestamp = System.currentTimeMillis(); likes = 0;
comments = new ArrayList();
}
public void addComment(String text) … public void like() …
public void display() …
… // some other code not shown
}
MessagePost source code
(just the outline – not all code is shown here)
11

FIT9131 Week 12
PhotoPost source code
(just the outline)
Can you spot the similarity/duplications in the code structure between the 2 classes?
12
public class PhotoPost
{
private String username;
private String filename;
private String caption;
private long timestamp;
private int likes;
private ArrayList comments;
public PhotoPost(String author, String filename, String caption)
{
username = author;
this.filename = filename;
this.caption = caption;
timestamp = System.currentTimeMillis(); likes = 0;
comments = new ArrayList();
}
public void addComment(String text) … public void like() …
public void display() …

}

FIT9131 Week 12
Side
13

by

side Comparison
public class MessagePost {
private String username;
private String message;
private long timestamp;
private int likes;
private ArrayList comments;
public MessagePost(String author, String text)
{
}
username = author;
message = text;
timestamp = System.currentTimeMillis(); likes = 0;
comments = new ArrayList();
public void addComment(String text) … public void like() …
public void display() …

}
public class PhotoPost {
private String username;
private String filename;
private String caption;
private long timestamp;
private int likes;
private ArrayList comments;
public PhotoPost(String author, String filename,
String caption)
{
}
username = author;
this.filename = filename;
this.caption = caption;
timestamp = System.currentTimeMillis();
likes = 0;
comments = new ArrayList();
public void addComment(String text) …
public void like() …
public void display() …

}

FIT9131 Week 12
NewsFeed
class
14
public class NewsFeed
{
private ArrayList messages; private ArrayList photos;

public void show()
{
for(MessagePost message : messages)
{
message.display();
System.out.println(); // empty line between posts }
for(PhotoPost photo : photos)
{
photo.display();
System.out.println(); // empty line between posts }
} }
Note the code duplications in client class as well

FIT9131 Week 12
Critique of Network class design
• Code duplications :
➢MessagePost and PhotoPost classes are very similar (large parts are identical) – because they are both just different types of “posts”
➢makes maintenance difficult / more work
➢introduces danger of bugs through incorrect maintenance (eg. change code in one class but forgot to change the other)
• There are code duplications in NewsFeed class too. 15

FIT9131 Week 12
Improved Design : Inheritance
Better solution :
Create a “superclass” (Post) to hold the common attributes/methods, then
use this to make the “subclasses” (MessagePost & PhotoPost).
This is the essence of Inheritance.
Note how the subclasses are now much simpler in design?
16

FIT9131 Week 12
Using inheritance
• define one superclass : Post
• define two subclasses : MessagePost and PhotoPost
• the superclass defines the common attributes (via fields) and common methods
• the subclasses inherit the superclass’s attributes/methods
• the subclasses then add other attributes/methods which
are specific to the subclasses themselves
17

FIT9131 Week 12
Using inheritance
Inheritance is sometime called an “is-a” relationship. e.g. a MessagePost is a Post, a PhotoPost is a Post.
superclass/subclass are often also known as parent/child classes, or base/derived classes.
In short, inheritance allows us to create classes which are similar to each other, without duplicating much of the code which is common to both classes.
18

FIT9131 Week 12
Example : Inheritance hierarchies
19
we can now say things like : • a dog is a mammal
• a chicken is a bird
• a poodle is a dog
• a poodle is a mammal • a poodle is an animal • etc….

FIT9131 Week 12
Coding Inheritance in Java
nothing special in the superclass header here
public class Post
{
… }
public class PhotoPost extends Post {
… }
public class MessagePost extends Post {
… }
20
use the keyword “extends” in the subclass headers here, to indicate that these 2 classes “inherit” from a superclass

FIT9131 Week 12
Superclass
public class Post
{
private String username;
private long timestamp;
private int likes;
private ArrayList comments;
// constructor and methods not shown
}
declaration
21
fields common to the subclasses

FIT9131 Week 12
Subclasses declaration
public class MessagePost extends Post {
private String message;
// constructor and methods not shown
}
public class PhotoPost extends Post
{
private String filename; private String caption;
// constructor and methods not shown
}
fields specific to the subclasses
22

FIT9131 Week 12
Access rights with inheritance
Generally, public members of a class (fields, methods and constructors) are accessible to objects of other classes.
Generally, private members are inaccessible to objects of other classes. They are only accessible to methods within the class that they belong to.
These same rules also apply between superclass and subclasses.
➢however, a subclass may call any public methods of its superclass as if they were its own.
23

FIT9131 Week 12
New : Protected access
Declaring a field or a method as protected allows direct access to it from (direct or indirect) subclasses.
Protected access is more restrictive than public access, since only subclasses can use those fields/methods.
Protected access may be applied to any member of a class – however, protected fields leads to weak encapsulation, and hence it is generally recommended to keep fields private and define appropriate accessors and mutators.
24

FIT9131 Week 12
Access levels between classes
25

FIT9131 Week 12
Inheritance and constructors
initialises the common attributes
26
Superclass :
public class Post
{
private String username;
private long timestamp;
private int likes;
private ArrayList comments;
/**
* Initialise the fields of the post.
*/ normal constructor)
public Post(String author)
{
username = author;
timestamp = System.currentTimeMillis(); likes = 0;
comments = new ArrayList();
}
// other methods not shown
}
nothing unusual in here (compared to a

FIT9131 Week 12
Inheritance and Subclass : constructors
initialises its own attribute
private String message;
/**
* Constructor for objects of class MessagePost */
public MessagePost(String author, String text) {
}
27
public class MessagePost extends Post {
super(author);
message = text;
}
// other methods not shown
the subclass’s constructor must call its superclass’s constructor (with the appropriate parameter(s)) to initialise the attributes in the superclass

FIT9131 Week 12
Superclass
Subclass constructors must always contain a ‘super’ call. This ‘super’ call must be the first statement in the subclass
constructor.
If no “super” call is written in the subclass’s constructor, the compiler automatically inserts one (without parameters):
➢this will only work if the superclass has a constructor without parameters – so is a potential source of error
➢so we should always include an explicit ‘super’ call in the subclass’s constructor – this is a good programming practice
28
constructor call

FIT9131 Week 12
Adding more Post types
it is now much easier to add new Post types.
the code for the common attributes/methods no longer needs to be repeated in the subclasses.
29

FIT9131 Week 12
Multiple
we could even extend the hierarchy further, if necessary

level hierarchies
30

FIT9131 Week 12
Advantages of inheritance
Inheritance (so far) helps with:
• avoiding code duplication
• code reuse – through subclassing an existing class
• easier maintenance – a change to a field or method that is shared between different classes needs to be made only once, in the superclass
• extendibility – easier to extend an existing class/application
31

FIT9131 Week 12
Old
NewsFeed
class (no inheritance)
32
public class NewsFeed
{
private ArrayList messages; private ArrayList photos;
public NewsFeed()
{
messages = new ArrayList();
photos = new ArrayList();
}
public void addMessagePost(MessagePost message) {
messages.add(message);
}
public void addPhotoPost(PhotoPost photo) {
photos.add(photo); }
// continued on next slide…

FIT9131 Week 12
Old
NewsFeed
class (no inheritance)
// continued from previous slide…
public void show() {
for(MessagePost message : messages)
{
message.display();
System.out.println();
}
for(PhotoPost photo : photos)
{
photo.display();
System.out.println(); }
} }
33

FIT9131 Week 12
Revised NewsFeed class (with inheritance)
Note how the code duplications in this client class has now disappeared!
Now a “Post” can be either a Message post, or a Photo post.
public class NewsFeed {
private ArrayList posts;
/**
* Construct an empty news feed.
*/
public NewsFeed()
{
posts = new ArrayList();
}
/**
* Add a post to the news feed.
*/
public void addPost(Post post) {
posts.add(post);
}
// continued on next slide…
34

FIT9131 Week 12
Revised inheritance)
class (with
NewsFeed
// continued from previous slide…
public void show()
{
for (Post post : posts)
{
post.display();
System.out.println(); }
} }
35
compare this method to the old (non-inheritance) version, where the 2 different types of “posts” had to be handled separately, by 2 separate loops.

FIT9131 Week 12
Subtyping
With no inheritance, we had:
public void addMessagePost(MessagePost message) public void addPhotoPost(PhotoPost photo)
With inheritance, we have:
public void addPost(Post post)
We can then call this method with something like:
PhotoPost myPhoto =
new PhotoPost(“David”, “dog.jpg”, “my dog’s photo”);
in the Network project
feed.addPost(myPhoto);
36
this adds a “photo” post (a PhotoPost object) to a “feed” (a NewsFeed object)

FIT9131 Week 12
37
Subtyping
• Subclasses define subtypes
• important principle : Objects of subtypes can be used wherever objects of their supertypes are expected
➢eg. feed.addPost(myPhoto);
• this is called type substitution
Subclasses and
• Classes define types
the addPost method expects a Post object as a parameter, but was given a PhotPost object here instead

FIT9131 Week 12
The inheritance hierarchy
So a NewsFeed object contains an ArrayList of Post objects, where each Post object can either be a MessagePost or a PhotoPost object. We no longer need 2 separate lists to store 2 different types of posts.
This design looks much better now, but are there any potential issues?
38

FIT9131 Week 12
Potential problem :
may generate confusing output…
display()
method
Leonardo da Vinci
Had a great idea this morning.
But now I forgot what it was. Something to do with flying … 40 seconds ago – 2 people like this.
No comments.
Alexander Graham Bell
[experiment.jpg]
I think I might call this thing ‘telephone’. 12 minutes ago – 4 people like this.
No comments.
Expected Output
Leonardo da Vinci
40 seconds ago – 2 people like this.
No comments.
Alexander Graham Bell
12 minutes ago – 4 people like this.
No comments.
Actual Output
39

FIT9131 Week 12
What causes this problem??
• inheritance is like a one-way street:
➢a subclass inherits its superclass’s fields, but
➢the superclass knows nothing about its subclass’s fields
• hence the display() method in Post can only prints the common fields, since it does not know what additional fields are present in the subclasses (PhotoPost & MessagePost). This is why part of the required output is missing!
40

FIT9131 Week 12
Solution 1 : move method into subclasses
• movedisplay()towhereit has access to the information it needs (in the subclasses)
• each subclass now has its own version of display()
• new problems :
➢Post’s fields are private
➢NewsFeed now cannot find a display() method in Post!!
display()
41

FIT9131 Week 12
Static type and dynamic type
• a more complex type hierarchy requires further concepts to describe it
• some new terminologies: ➢static type
➢dynamic type ➢polymorphism ➢method dispatch/lookup
42

FIT9131 Week 12
Example : Static and dynamic types
Vehicle
43
Car c1 = new Car();
Vehicle v1 = new Car();
What is the type of c1? What is the type of v1?
Car
Bicycle

FIT9131 Week 12
Static and dynamic types
The declared type of a variable is its static type.
The (real/actual) type of object a variable refers to at run-time is its dynamic type.
Therefore, in the previous example:
c1 has a static type of Car and a dynamic type of
Car
versus :
v1 has a static type of Vehicle and a dynamic
type of Car 44

FIT9131 Week 12
Static and dynamic type
• summary :
➢the declared type of a variable is its static type
➢the type of the actual object a variable refers to is its dynamic type
• the compiler’s job is to check for static-type violations.
eg. in the NewsFeed class shown earlier, if we used :
for (Post post : posts)
{
post.display(); // Compile-time error.
(there is no display() in Post class)
}
45

FIT9131 Week 12
Solution 2 : Method Overriding
Place display() in both superclass and subclasses.
46
Satisfies both static and dynamic type checking.

FIT9131 Week 12
Method Overriding
• a subclass can override the implementation of a method it inherits from its superclass.
• superclass and subclass define methods with the same signatures. Note : this is different from the method overloading discussed in a previous lecture.
• each method has access to the fields of its class.
• superclass method satisfies static type check.
• subclass method is called at runtime – it overrides the superclass version.
• what happens to the superclass version then? 47

FIT9131 Week 12
Polymorphism
In Object-oriented programming, the term “Polymorphism” is often used to describe variables/objects or methods which can exist in multiple forms.
• In Java :
➢a polymorphic variable is one which can store
objects of varying types.
➢a polymorphic method call is one which can invoke different methods at different times.
• More details about this concept to follow… 48

FIT9131 Week 12
Method Lookup process
49
If no inheritance or polymorphism is used, the obvious method in the superclass is selected.

FIT9131 Week 12
Method Lookup process
50
Inheritance but no overriding. The inheritance hierarchy is ascended, searching for a match.

FIT9131 Week 12
Method Lookup process
51
PhotoPost v1;
Polymorphism and overriding. The ‘first’(or closest) version found is used.

FIT9131 Week 12
Method lookup summary
When a method (belonging to an object) is called, the following happens :
1) the variable is accessed
2) the object stored in the variable is found
3) the class of the object is found
4) the class is searched for a method match
5) if no match is found, the superclass is searched
6) this is repeated until a match is found, or the class hierarchy is exhausted
7) overriding methods take precedence
52

FIT9131 Week 12
Using “super” call in overridden methods
• overridden methods in a superclass are hidden from the subclasses …
➢but we often still want to be able to call them
• an overridden method can be called from the method that overrides it by preceding the method call with the keyword “super” :
➢super.method(…)
➢compare this with the use of super(…) in
constructors of subclasses
53

FIT9131 Week 12
Example : Calling an overridden method from within a subclass
public void display() {
super.display();
subclass’s display() method calling the superclass’s
display() method
54
System.out.println(” [” + filename + “]”);
System.out.println(” ” + caption); }

FIT9131 Week 12
Method/variable polymorphism • we have been discussing polymorphic method calls.
➢the actual method called depends on the dynamic object type.
• we can also have polymorphic variables.
➢a polymorphic variable can store objects of
varying types
➢a polymorphic variable can store an object of its declared type, or an object of a subtype of its declared type (eg. the variable v1 in the previous example, which could store either a Vehicle object, or a Car object)
55

FIT9131 Week 12
Revised Object diagram (with inheritance)
Note : now a “Post” can be either a Message post, or a Photo post. The posts arraylist in NewsFeed only knows that it is storing some kind of “Post” objects.
56

FIT9131 Week 12
Compare : old Network Object model
(with
57
no inheritance)
The design is a lot more complicated, with a lot of code duplications.

FIT9131 Week 12
Revised Class diagram (with inheritance)
58

FIT9131 Week 12
Type Casting
• we can assign subtype to supertype … • … but we cannot assign supertype to
subtype! Eg :
Vehicle v;
Car c = new Car(); v = c; // correct
c = v; // compile-time error!
• “casting” fixes this: c = (Car) v;
this is known as “casting” (the parentheses are not optional) – you have actually seen this technique with the primitive types.
59
(only works if the vehicle really is a Car!)

FIT9131 Week 12
Casting
• specify an object type in parentheses to perform casting :
➢stops the compiler from generating a compile- time error
➢the original object is not changed in any way • Java makes check at run-time ensure the object
really is of that type: ➢ClassCastException thrown if it isn’t!
• good design principle : use casting sparingly. Frequent manual casting often indicates possible design flaws.
60

FIT9131 Week 12
The Java
Object
class
All Java classes inherit from the Object class.
61

FIT9131 Week 12
Review
• Inheritance allows the definition of classes as extensions of other classes.
• Inheritance benefits :
➢avoids code duplication
➢allows code reuse
➢simplifies the code
➢simplifies maintenance and extending
• variables can hold subtype objects.
• subtypes can be used wherever supertype objects
are expected (substitution). The reverse is not true.
62

FIT9131 Week 12
Multiple Inheritance
• Some OO languages (not Java) support the concept of multiple-inheritance. This simply means that a subclass can inherit from more than one superclasses.
Eg :
This means a monster is both a mammal and a bird!
Animal
Mammal
Bird
63
Dog
Cat
Monster
• this is sometimes useful, but can also create some complications and other problems
Duck
Turkey

FIT9131 Week 12
64
Java and Multiple Inheritance
• Java does not support multiple-inheritance : ➢a Java subclass cannot inherit from more than one
superclass
➢however, multiple-inheritance can be “simulated” to some degree via some special Java constructs
• we have not covered this rather advanced concept in this unit

FIT9131 Week 12
Final Exam Format
• Exam is worth 60% of the total marks for the unit
• Exam duration : 2 hrs and 10 mins
• All answers to be entered into the e-exam system.
• The exam is open book. You can refer to reference materials but the responses to the questions must be your own work.
65

FIT9131 Week 12
Final Exam Format
There are three sections on the exam:
➢Section A (Short response questions: code interpretation, code writing, theory) : ~32 marks
➢Section B (Debugging questions) : ~18 marks ➢Section C (Coding) : ~50 marks
66

FIT9131 Week 12
Exam Study Tips
Suggestions on how to prepare for the Final Exam :
• re-do all your tute exercises, without looking at your previous answers :
• form study groups with other students, and compare/discuss each others’ notes and solutions.
• read through all the lecture notes, making sure you understand all the concepts presented in them.
• study your Assignments (both design and coding)
• practice with the Sample Exam to see what type of
questions to expect. Do not memorise the sample paper!
67

FIT9131 Week 12
Answering exam questions
• the number of marks allocated to a question is generally a rough guide (or hint) to how complex the answer is… eg. a 10-mark question would generally not require a 15-page, one-hour, answer!
• read the question carefully – an excellent answer to the wrong question will not score any marks!
68
68

FIT9131 Week 12
Answering exam questions
• follow the instructions – eg. if the question asks you to describe 3 things, do not describe more than 3 (only the first 3 answers will be marked)!
• if you cannot completely answer a question, do not just skip it entirely – answer the part(s) that you do understand, to earn at least some marks.
• do not change the question to suit your answer!
69
69

FIT9131 Week 12
Pre
• Pre-exam consultation will be scheduled in week 13 and week 14.
• Please refer to Moodle for more details.

exam Consultation
70