Topic 2: Advanced Java – objects,
composition, inheritance
Sub Topic 2: Reuse – Composition and Inheritance
ICT373: Software Architectures
Copyright By PowCoder代写 加微信 powcoder
• Java overview • Objects
• Java revision
• O-O design and The Unified Modelling Language (UML)
• Reuse and Packages
• Composition (or aggregation)
• Inheritance, Polymorphism, Dynamic Binding
• Abstract Classes and Inner Classes
• Collections
• Exception Handling
Textbook (11th ed.) Chapters 9, 10, 11, 14, 16 and 20
Objectives (1/3)
• Describe and explain the use of: abstraction, encapsulation, information-hiding, localization and name management.
• Use packages in Java.
• Explain the use of access modifiers in Java.
• Explain the term composition and be able to represent it in UML.
• Implement composition in Java including initialization of components.
• Explain inheritance and be able to represent it in UML.
• Implement inheritance in Java including initialization.
• Use, explain and implement overriding in Java.
• Make basic use of ‘this’ and ‘super’.
Objectives (2/3)
• Explain the need for and use of the class Object.
• Correctly choose between composition and inheritance in a design.
• Explain the concepts of polymorphism and dynamic binding.
• Explain upcasting and downcasting and how to implement them in Java.
• Explain the uses for and use of abstract classes, interfaces and the ‘final’ keyword.
• Describe multiple inheritance and how it can be implemented in Java.
• Explain what is an inner class? Explain the uses of inner classes.
• Explain what is a call-back function? Explain the use of call-back functions.
Objectives (3/3)
• Explain the Java Collections Framework.
• Describe the use of data structures like collections in Java and the use of iterators.
• Explain the use of generics and enhanced for loop in Java.
• Explain how exceptions are handled in Java.
Objects, composition, inheritance
Abstraction, Encapsulation and Re-use
• Important elements of OOSE.
• Abstraction: dealing with the essential features of something while ignoring the detail.
• eg, defining a class instead of dealing with a bunch of separate objects.
• Encapsulation: providing things with a protected inside
• eg, having a public interface so that client users do not need
to know about the inner workings.
• Information-hiding: hiding or encapsulating the details
• Localization: allowing changes inside a class/object/thing to be made while the public interface is unaffected.
• Name-management: preventing confusion and clashes with identifier names
Abstraction, Encapsulation and Re-use
• Reuse: using the existing classes without changing their code:
• Inheritance
• composition
• packages
• Collection
• Design patterns
Abstraction, Encapsulation and Re-use
Composition: simply create objects of your existing class inside the new class, meaning that the new class is composed of objects of existing classes. You are reusing the functionality of the code, not its form.
Inheritance: involves creating a new class as a type of an existing class. i.e., you take the form of the existing class and add code to it without modifying the existing class.
Abstraction, Encapsulation and Re-use
• Inheritance is implemented in Java with the extends keyword.
• You make a new class (derived class) and you say it extends an existing class (base class)
• Note that inheritance is an integral part of all OOP languages.
• In java, we always use inheritance when a class is created, because unless we explicitly inherit from some other class, we implicitly inherit from Java’s standard root class Object.
• Overall, OO Languages, i.e. languages which support these ideas, support reuse and pluggable components. This helps with speed and correctness of design and implementation.
• Java supports these ideas at a class level.
Libraries and Packages
• Java also supports encapsulation above the class level with the
package feature.
• A package is a collection of related classes that have been
grouped together in a directory (and given a package name):
• which may contain classes private to the package (supporting encapsulation) – to be used only by package classes; and
• public classes – which can readily be imported together for use by other classes (supporting reuse).
• To make a package available we need to use import keyword, e.g.
import java.util.*;
Libraries and Packages
• Many useful packages already exist and are ready for use by implementers as libraries. These include the standard class libraries (which we have met), e.g., Java API packages java.lang, java.util, javax.swing and Java Collection classes.
• Reuse also requires good documentation. A special feature of Java libraries is the ease of use of javadoc to directly generate online and fully cross-linked HTML descriptions.
• Documentation is an important part of the public interface of an encapsulated class.
Package usage (1/3)
• Before a class can be imported into multiple applications, it must be placed in a package.
• In order to use a class in a package
• the class must be declared to be part of the package (the class’s first
statement)
• the package must be in the right directory
• the class must be imported by the client class
• To declare a class A as part of a package X.Y put
• package X.Y;
• as the first statement in the source file for class A.
• (If there is no such declaration then the class belongs to a package called
the default package and all such classes belong to that same package.)
• Also, the class A must be declared a public class (otherwise it can only be used by other classes in this package).
Package usage (2/3)
• The classes belonging to a package must be compiled. Then make sure that all the .class files in the package are placed in an appropriate directory, eg
\myclassdirectory\X\Y
and that the operating system’s environment variable
CLASSPATH includes \myclassdirectory
• For further information on the classpath, see:
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/class path.html
Package usage (3/3)
Once the class is compiled and stored in its package, put import X.Y.A; or
import X.Y.*;
in the client source file and refer to class A. Or, in the client, refer to the class as X.Y.A
The designers of Java recommend that a package name should start with your internet domain name in reverse order to provide unique names for packages. Eg, the package statement
package au.murdoch.it.ict373.topic4;
indicates that the class be placed in directory au\murdoch\it\ict373\topic4
Access to Top Level Classes
• Access modifiers are available to support encapsulation.
• A top level class is a class which appears in a source file not nested inside another class.
• These top level classes can have their access/visibility declared as
• public – meaning that this class can be used by any other class. (Note that there can only be at most one top level class declared as public in any source file.) OR
• there may be no declaration in which case this top level class can only be accessed within the package.
• This is sometimes called “friendly” access.
General Access Modifiers
• save clients from having to know all about your implementation;
• stop clients from using things that you might want to change;
• stop clients from using methods (or changing variables) which should only be used very carefully in certain circumstances at the risk of making your program run incorrectly;
• hide local things to help prevent name clashes.
Composition
• One way of (re-)using another class B is to have a member variable of type B as part of the definition of your class A.
• This is known as composition. It is the “has-a” relationship.
• Each object of class A has an object of class B as part of itself.
• For example, a staff member object might have an address object and each address object might have a postcode object.
• Note that composition between classes is an example of an association which should be recorded as part of the design.
• Composition in UML,
• Class A has a member variable of type B (and maybe lots of other member
variables).
• Note that this means that constructing an A object requires construction of a B object.
(big objects)
(small objects)
Inheritance
• We might want to say that each object of class B is also an object of class A, i.e. it has all the variables and methods that A objects have but it may have more.
• This is the “is-a” relationship.
• Class B is a bit more specific in its details. Class A is known as the superclass (base class in C++), class B as the subclass (derived class in C++).
• For example, in a library system, a reference book is a book. In UML,
(super class)
Reference Book (sub class)
Inheritance in Java
• We use the following syntax:
class ReferenceBook extends Book { method and variable declarations }
• Objects of the subclass type (e.g. ReferenceBook) will then have all the methods and variables of the Book class plus any extra ones which have been declared as belonging to ReferenceBooks.
• You do not need to re-declare the superclass methods and variables (unless you want to change the body of a method).
Inheritance in Java
• If Book has a getTitle() method and bk1 contains a reference to a ReferenceBook, then you can call
bk1.getTitle();
and the method body defined in the Book class will be executed for the ReferenceBook. This will work because the ReferenceBook has all the other variables and methods that books are supposed to have.
• The methods defined specifically for ReferenceBooks can also call the Book methods, e.g. the method
printRedLabel();
(defined only for Reference books) can call
str = getTitle();
Initialize a member variable
• an initialization expression in the declaration int i = 25;
• a statement immediately after the declaration
• assignment inside the constructor for class A
• default, primitives get a 0 value, other types get a null reference.
Overriding (vs Overloading)
• We can also re-define methods inside ReferenceBook. Eg, Books might have a borrow() method but we can also give ReferenceBooks a new definition for a borrow() method which might just give an error message on a screen saying that the book can not be borrowed.
• This is known as overriding because calling the method on a subclass object will result in the subclass definition being used. The more general method is overridden.
• Note: do not get overriding confused with overloading, which is using the same name for several different methods but distinguishing them by the number of, and/or types of their arguments.
Overriding (vs Overloading)
Static vs dynamic binding
Access: private vs protected
• Subclass methods have no access to the private methods or private members of the superclass.
• Eg, the implementer of the ReferenceBook class may not be able to change the location of a ReferenceBook in a ReferenceBook method except by calling the appropriate methods supplied with the Book class.
• If the implementer of the superclass wants to allow subclass methods to access some variables or methods then they should be declared as protected.
Inheritance and constructors
• If class B extends class A then construction of a B object involves, in a certain sense, the construction of an A object. In fact, the basic A object should be built first and the extra B bits added on afterwards.
• Suppose a B object (derived from A) is newly created in a program.
• If the B programmer does not explicitly request anything else, then the first step after memory allocation, is for the default constructor for A objects to be called.
• When the A constructor is finished then the initializations in the B definition are executed.
• Then body of the B constructor is executed.
this keyword (1/2)
• Recall that a constructor is used when client code uses the new
keyword. Eg,
b = new B();
uses the constructor B() in the class B to build a new B object and puts a reference to it in the variable b.
• A constructor with no arguments is called a default constructor.
• You can write your own constructor, or,
• if you provide a class with no constructors then Java will automatically provide a default constructor for the class.
• Note, if you write any constructors then none will be supplied automatically.
this keyword (2/2)
• You can also provide constructors which do have arguments. Eg,
B( int n ) { constructor body using n}
and the client can use b = new B(7);
• If you have lots of constructors then they are distinguished by the
number and types of arguments.
• If you are supplying several constructors then one can use another by
means of the this keyword. Eg, B (int n, char c)
{ this(n); initial=c; }
• Here a call to new B(7, ‘a’) results in the constructor call B(7) happening first to make the new B object, and then the initial field being given the value in the variable c.
Static vs dynamic binding
• Static binding in Java occurs during Compile time while Dynamic binding occurs during Runtime.
• private, final and static methods and variables uses static binding and bonded by compiler while virtual methods are bonded during runtime based upon runtime object.
• Static binding uses Type(Class in Java) information for binding while Dynamic binding uses Object to resolve binding.
• Overloaded methods are bonded using static binding while overridden methods are bonded using dynamic binding at runtime.
super keyword
• If B is a subclass of A then we know that an A object will be built first
before being turned into a B object.
• How do we control which A constructor is used?
• When new B(args) is called, then immediate appearance of this inside the B(params) constructor, might cause another B constructor to be called first.
• Since recursion is not allowed here, eventually the last B constructor to be called is called.
• Now an A constructor (with empty parameter list) will be called unless the B constructor starts with a call to super(args). This will result in the A constructor with matching parameters being called.
• Note that both super and this have other uses:
• Naively, this gives access to the current object (which owns the method that the code is in) and super gives access to the superclass version of the current object.
thisvssuper.Java example
/* test results:
-1 <- a non printable char is outputted here for the
uninitialised variable ‘initial’
7a ------------------------------------------------- 7
Class Hierarchies
• For various reasons (e.g., garbage collection and collection classes), it is useful to have a single-rooted inheritance hierarchy, i.e. all objects belong to one class.
o In Java all other classes inherit from the class called Object (found in library java.lang) but it is not necessary to declare that your classes extend Object.
o all objects have the methods which belong to the Object class (e.g., clone() - for copying, equals for comparing two objects for equality, getClass() - for class determination during runtime, finalize() - for garbage collection, toString() - for string representation, and wait(), notify(), notifyAll() - to handle multithreading)
o any object can be referred to by a variable of Object type (e.g., data structures can be built which can contain elements of any type).
o Note that arrays are Objects too and so these two properties apply to them as well.
When to use composition instead
• We have said that inheritance is a way of getting B objects to be just like A objects but with a few extras.
• This allows us to re-use the A code and allows us to re-use the A public interface (ie the public methods).
• If it is really only code re-use that you are after, and not interface re-use, then it may be better (more correct) to use composition instead of inheritance.
• Thus we might put an A object inside as part of each B object. All the functionality (and code) of the A object is then available to the B implementer, but they can hide all of this inside a public interface which is just right for B objects.
• a coloured square is a square with colour (inheritance);
• a circle has a centre point (composition);
• a professor is a staff member (inheritance);
Polymorphism
• How can inheritance be used?
• Suppose class B extends class A. This means that B objects can be used where an A object would be expected. The B object can be upcast to being an A object.
Eg, Variables of type A can refer to objects of type B.
B varb = new B();
vara = varb; // upcasting – an A object was expected here Eg, methods of class A can be called on B objects. System.out.println( varb.name() );
assuming that class A has a public name() method of String return type.
Polymorphism
• Being able to use a facility (variable, method, function etc) with
different types of arguments is called polymorphism.
• This is a basic feature of O-O languages and O-O design. It allows
re-use of public interfaces and code in a very convenient form. Eg, window.repaint(); (buttons, frames, dialogues, ...) account.debit(n); (savings, cheque, credit, ...) memb.printAddrLabel(); (staff, student, postgrad, ...)
Static vs dynamic binding(1/3)
Static vs dynamic binding(2/3)
Static vs dynamic binding(3/3)
• Static binding in Java occurs during Compile time while Dynamic binding occurs during Runtime.
• private, final and static methods and variables uses static binding and bonded by compiler while virtual methods are bonded during runtime based upon runtime object.
• Static binding uses Type(Class in Java) information for binding while Dynamic binding uses Object to resolve binding.
• Overloaded methods are bonded using static binding while overridden methods are bonded using dynamic binding at runtime.
Downcasting
• Dynamic binding does not mean that the compiler gives up completely on type-checking of expressions. Methods and types of variables are checked just as thoroughly.
• Suppose that class B extends class A and that B has an extra() method which A does not have. The following code will not compile
A vara; // class A object
vara = new B(); // class B object is assigned to A variable vara.extra(); // class A does not have this method –
// vara has to be downcast first
because the compiler does not think that A objects have extra methods.
Downcasting
• There are situations in which we upcast (and so lose some type information) and then, later, want the type information back again.
• To do this we must downcast, i.e. start referring to an object by a more detailed reference. Unlike, upcasting, downcasting involves explicit mention of the class:
( (B)vara ).extra();
• Upcasting from B to A can always be done. However, downcasting involves a risk of a run-time error: trying to cast an A type of object to a B reference although the object is not a B object. Programmer beware.!!
Abstract classes
• Abstract classes are intended to be used only as superclasses. They can not be used to instantiate objects. They are regarded as too generic (or incomplete) to create real objects.
• An abstract class normally contains one or more abstract methods.
• Suppose we have a bunch of similar class types B, C and D. Say that they share a lot of public interface and maybe some implementation. You sometimes want to treat them alike.
• A good design is to identify the common interface, call it class A, and make B, C and D all extend A.
• A client can then treat them all using A methods and A references when it is convenient.
• Often, you do not even want there ever to be any A objects in existence.
• In that case class A can be made abstract by declaring it with keyword abstract: abstract class A { fields and methods }
Abstract classes
• The compiler will complain if someone tries to construct an A object. (But you can have many A variables.)
• You may want B, C and D to all have a common(n) method and to put that in class A but they may all implement it
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com