120
Inheritance tMyn 1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing them with new or modified capabilities. With inheritance, programmers save time during program development by reusing proven and debugged high-quality software. This also increases the likelihood that a system will be implemented effectively.

InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Embed Size (px)

Citation preview

Page 1: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 1

Inheritance

• Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing them with new or modified capabilities.

• With inheritance, programmers save time during program development by reusing proven and debugged high-quality software.

• This also increases the likelihood that a system will be implemented effectively.

Page 2: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 2

• When creating a class, rather than declaring completely new members, the programmer can designate that the new class should inherit the members of an existing class.

• The existing class is called the base class, and the new class is the derived class.

• Each derived class can become the base class for future derived classes.

• A derived class normally adds its own fields and methods.

• Therefore, a derived class is more specific than its base class and represents a more specialized group of objects.

Page 3: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 3

• Typically, the derived class exhibits the behaviors of its base class and additional behaviors that are specific to the derived class.

• The direct base class is the base class from which the derived class explicitly inherits.

• An indirect base class is any class above the direct base class in the class hierarchy, which defines the inheritance relationships between classes.

• In Java, the class hierarchy begins with class Object (in package java.lang), which every class in Java directly or indirectly extends or inherits from.

Page 4: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 4

• All the classes that you define are derived classes by default – whether you like it or not.

• You never need to specify the class Object as a base class in the definition of your classes – it happens automatically.

• There are some interesting consequences of having Object as a universal base class. The discussion of those topics are beyond this module.

Page 5: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 5

• In the case of single inheritance, a class is derived from one direct base class, Figure 1.

• Java does not support multiple inheritance.• In Java programmers can use interfaces to realize many

of the benefits of multiple inheritance while avoiding the associated problems.

Page 6: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 6

HorseVehicle

WagonChaise

Single Inheritance

Figure 1. An example of an UML representation of the single inheritance.

Page 7: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 7

• We can use a Box class to describe a rectangular box – our definition of a Box object consists of just the three orthogonal dimensions.

• We might describe a Carton class which has the same properties as a Box object plus the additional property of its composite material.

• We might then specialize even further, by using the Carton definition to describe a class called FoodCarton – this will be a special kind of Carton which is designed to hold food, Figure 2.

Page 8: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 8

lengthbreadthheight

lengthbreadthheightmaterial

lengthbreadthheightmaterialcontents

class FoodCarton

class Box

class Carton

Inheritedmembers

Inheritedmembers

MoreGeneral

MoreSpecialized

Each class has the properties of the class it is derived from, plus additional properties that differentiate it.

Figure 2. An example of a three level class hierarchy.

Page 9: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 9

• The Carton class is an extension of the Box class – you might say that the Carton class is derived from the specification of the Box class.

• In a similar way, the FoodCarton class has been derived from the Cartoon class.

• By following this process, we develop a hierarchy of interrelated classes.

• In the hierarchy, one class is derived from another by adding extra properties – in other words, by specializing.

Page 10: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 10

• Given a class A, suppose that we create a new, specialized class B.

• So the class A is called the base class and the B is called the derived class.

• The derived class automatically contains all of the instance variables of the base class, and (with some restrictions which we will discuss) all the methods.

• The derived class is said to inherit the instance variables and methods of the base class.

Page 11: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 11

• If class B is a derived class defined directly in terms of class A, then we say that class A is a direct base class of B.

• We also say that B is derived from A.• In the example above, the class Carton is a direct

base class of FoodCarton.• Because Carton is itself defined in terms of the class

Box, we say that the class Box is an indirect base class of the class FoodCarton.

• An object of the FoodCarton class will have inherited members from Carton – including the members that the Carton class inherited from the Box class.

Page 12: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 12

• In the diagram above, each class has all the properties of the Box class (on which it is based), and this illustrates precisely the mechanism of class inheritance.

• The derived class has a complete set of instance variables and methods from the base class, plus its own instance variables and methods.

• Thus, each derived class object contains a complete base class sub-object, plus other members.

• When does inheritance take place?• There are a number of simple tests that you can

employ.

Page 13: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 13

• The first is the is a kind of test: any derived class object is a kind of base class object.

• In other words, a derived class should describe a subset of the objects represented by the base class.

• For example: a class Dog might be derived from a class Animal. This makes sense because a dog is a kind of animal.

• The is a kind of test is an excellent first check, but it’s not infallible. For example, suppose that we defined a class, Bird, that (among other things) reflected the fact that most birds can fly…

Page 14: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 14

• …but now an ostrich is a kind of bird, but it’s nonsense to derive a class Ostrich from the Bird class, because ostriches can’t fly!!

• If your classes pass the is a kind of test, then you should double check by asking the following question: Is there anything I can say about (or demand of) the base class that’s inapplicable to the derived class?

• If there is, then the derivation probably isn’t safe.

Page 15: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 15

• If your classes fail the is a kind of test, then you almost certainly shouldn’t use class derivation.

• In this case, you could instead implement the has a test.

• A class object passes the has a test, if it contains an instance of another class.

• You can implement this situation by including an object of the second class as a data member of the first.

• This type of dependence is called aggregation or composition. Those topics will be discussed later.

Page 16: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 16

• For example, consider a class Automobile.• This class is likely to contain major automobile

components as its class members.• An automobile has an engine, has a transmission,

has a chassis and has suspension.• So it makes sense for the Automobile class to contain

objects of type Engine, Transmission, Chassis and Suspension.

• But it is not true to say that an engine is a kind of automobile!

• The first example demonstrates the fundamentals in a two level class hierarchy:

Page 17: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 17

package Timosoft;import java.util.Scanner;import java.util.Locale;public class Box{ double width, height, depth; Box() { System.out.println("Box constructor called."); setWidth(); setHeight(); setDepth(); } void setWidth() { Locale.setDefault(Locale.ENGLISH); Scanner fromTheKb1=new Scanner(System.in); System.out.print("Enter the width, please: "); width=fromTheKb1.nextDouble(); }

Page 18: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 18

void setHeight() { Locale.setDefault(Locale.ENGLISH); Scanner fromTheKb2=new Scanner(System.in); System.out.print("Enter the height, please: "); height=fromTheKb2.nextDouble(); } void setDepth() { Locale.setDefault(Locale.ENGLISH); Scanner fromTheKb3=new Scanner(System.in); System.out.print("Enter the depth, please: "); depth=fromTheKb3.nextDouble(); } double getVolume() { return width*height*depth; }}

Page 19: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 19

package Timosoft;import java.util.Scanner;import java.util.Locale;public class MatchBox extends Box{ double weight;

MatchBox() { super(); System.out.println("MatchBox constructor called."); setWeight(); }

Page 20: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 20

void setWeight() { Locale.setDefault(Locale.ENGLISH); Scanner fromTheKb4=new Scanner(System.in); System.out.print("Enter the weight, please: "); weight=fromTheKb4.nextDouble(); } double getWeight() { return weight; }}

Page 21: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 21

package Timosoft;

public class BoxTest{ public static void main(String[] args) { Box first=new Box(); System.out.println("The volume of the Box object is "+ first.getVolume()); MatchBox second=new MatchBox(); System.out.println("The weight of the MatchBox object is "+ second.getWeight()); System.out.println("The volume of the MatchBox object is "+ second.getVolume()); }}

Page 22: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 22

Box constructor called.Enter the width, please: 1.23Enter the height, please: 4.56Enter the depth, please: 7.89The volume of the Box object is 44.253432Box constructor called.Enter the width, please: 0.12Enter the height, please: 3.45Enter the depth, please: 6.78MatchBox constructor called.Enter the weight, please: 9.01The weight of the MatchBox object is 9.01The volume of the MatchBox object is 2.80692BUILD SUCCESSFUL (total time: 1 minute 7 seconds)

Page 23: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 23

• From the preceding example:• From the class Box we have derived a MatchBox class:

public class MatchBox extends Box

• The extends keyword identifies that Box is a base class for MatchBox, so an object of type MatchBox will have members that are inherited from the Box class, in addition to the members of the MatchBox class that appear in its definition.

Page 24: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 24

• The constructor for the base class constructs the base class portion of the object (so when creating an object to the base class that is all there is), and the constructor for the derived class constructs the derived class part.

• This makes sense because the base class has no knowledge of or access to any element in a derived class.

• Thus, their construction must be separate. Each class does have its own constructors, derived class does not inherit the base class constructors.

• Constructors are not inherited, but the constructor of the base class can be invoked from the derived class.

Page 25: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 25

• You should always call an appropriate base class constructor from the constructors in your derived class.

• The base class constructor call must be the first statement in the body of the derived class constructor.

• If the code does not include an explicit call to the base class constructor, Java implicitly calls the base class’s default or no-argument constructor.

• The base class constructor call syntax is keyword super followed by a set of parentheses () containing the base class constructor arguments.

• When a base class contains a no-argument constructor, you can use super() to call that constructor explicitly, but that is not a must.

Page 26: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 26

• Let us modify the previous example: now there are constructors with parameters in both the base class and the derived class.

• Any form of constructor defined by the base class can be called by super().

• The constructor executed will be the one that matches the arguments:

Page 27: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 27

package TimoSoft;import java.util.Scanner;import java.util.Locale;public class Box{ double width, height, depth; Box() { System.out.println("Box default constructor called."); setWidth(); setHeight(); setDepth(); } Box(double wVal, double hVal, double dVal) { System.out.println("Box constructor with 3 params. called."); setWidth(wVal); setHeight(hVal); setDepth(dVal); }

Page 28: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 28

void setWidth() { Locale.setDefault(Locale.ENGLISH); Scanner fromTheKb1=new Scanner(System.in); System.out.print("Enter the width, please: "); width=fromTheKb1.nextDouble(); } void setHeight() { Locale.setDefault(Locale.ENGLISH); Scanner fromTheKb2=new Scanner(System.in); System.out.print("Enter the height, please: "); height=fromTheKb2.nextDouble(); } void setDepth() { Locale.setDefault(Locale.ENGLISH); Scanner fromTheKb3=new Scanner(System.in); System.out.print("Enter the depth, please: "); depth=fromTheKb3.nextDouble(); }

Page 29: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 29

void setWidth(double w) { width=w; } void setHeight(double h) { height=h; } void setDepth(double d) { depth=d; } double getVolume() { return width*height*depth; }}

Page 30: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 30

package TimoSoft;import java.util.Scanner;import java.util.Locale;public class MatchBox extends Box{ double weight;

MatchBox() { super(); System.out.println("MatchBox default constructor called."); setWeight(); } MatchBox(double weVal) { super(); System.out.println("MatchBox constructor with 1 param. called."); setWeight(weVal); }

Page 31: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 31

MatchBox(double wiVal, double heVal, double deVal) { super(wiVal, heVal, deVal); System.out.println("MatchBox constructor with 3 param. called."); setWeight(); } MatchBox(double wiVal, double heVal, double deVal, double weVal) { super(wiVal, heVal, deVal); System.out.println("MatchBox constructor with 4 param. called."); setWeight(weVal); } void setWeight() { Locale.setDefault(Locale.ENGLISH); Scanner fromTheKb4=new Scanner(System.in); System.out.print("Enter the weight, please: "); weight=fromTheKb4.nextDouble(); }

Page 32: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 32

void setWeight(double w) { weight=w; } double getWeight() { return weight; }}

Page 33: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 33

package TimoSoft;

public class Test{

public static void main(String[] args) { MatchBox third=new MatchBox(9.74); System.out.println("The weight of the MatchBox object third is "+ third.getWeight()); System.out.println("The volume of the MatchBox object third is "+ third.getVolume()); MatchBox fourth=new MatchBox(10.2, 20.4, 30.6); System.out.println("The weight of the MatchBox object fourth is "+ fourth.getWeight()); System.out.println("The volume of the MatchBox object fourth is "+ fourth.getVolume());

Page 34: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 34

MatchBox fifth=new MatchBox(1.23, 4.56, 7.89, 0.12); System.out.println("The weight of the MatchBox object fifth is "+ fifth.getWeight()); System.out.println("The volume of the MatchBox object fifth is "+ fifth.getVolume()); }}

Page 35: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 35

run:Box default constructor called.Enter the width, please: 6.6Enter the height, please: 8.8Enter the depth, please: 9.9MatchBox constructor with 1 param. called.The weight of the MatchBox object third is 9.74The volume of the MatchBox object third is 574.992Box constructor with 3 params. called.MatchBox constructor with 3 param. called.Enter the weight, please: 14.4The weight of the MatchBox object fourth is 14.4The volume of the MatchBox object fourth is 6367.248Box constructor with 3 params. called.MatchBox constructor with 4 param. called.The weight of the MatchBox object fifth is 0.12The volume of the MatchBox object fifth is 44.253432BUILD SUCCESSFUL (total time: 56 seconds)

Page 36: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 36

• As could be seen, constructors are called in order of derivation, from base class to derived class (when a derived class object was created).

• Further, since super() must be the first statement executed in a derived class’ constructor, this order is the same whether or not super() is used explicitly.

• If super() is not used, then the default (parameterless) constructor of each base class will be executed.

Page 37: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 37

• When a derived class calls super(), it is calling the constructor of its immediate base class.

• Thus, super() always refers to the base class immediately above the calling class. This is true even in a multilevel hierarchy.

• There is a second form of super that acts somewhat like this, except that it always refers to the base class of the derived class in which it is used.

• This usage has the following general form:

super.member

Page 38: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 38

• Here, member can be either a method or an instance variable.

• This form of super is most applicable to situations in which member names of a derived class hide members by the same name in the base class.

Page 39: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 39

• As stated earlier, the default access setting (in which no access specifier is used) is the same as public unless your program is broken down into packages.

• The primary purpose of public methods is to present to the class’s clients a view of the services the class provides (the class’s public interface).

• Clients of the class need not be concerned with how the class accomplishes its tasks.

• For this reason, the private instance variables and private methods of a class (i.e., the class’s implementation details) are not directly accessible to the class’s clients.

Page 40: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 40

• The next example (class definitions are extremely simple ones) demonstrates the public keyword usage, and the behavior is exactly the same as what it would be without this keyword.

• There is two level class hierarchy, and first an object is created to the base class:

Page 41: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 41

package TimoSoft;

public class A{ public int a; public A(int aVal) { System.out.println("A constructor called."); setA(aVal); } public void setA(int aValue) { a=aValue; } public int getA() { return a; }}

Page 42: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 42

package TimoSoft;

public class B extends A{ public int b; public B(int aVal, int bVal) { super(aVal); System.out.println("B constructor called."); setB(bVal); } public void setB(int bValue) { b=bValue; }

Page 43: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 43

public int getB() { return b; } public void getInfo() { System.out.println("The instance variable values a and b are: "+ a+" and "+b+"."); }}

Page 44: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 44

package TimoSoft;

public class Test{ public static void main(String[] args) {

A first=new A(1); System.out.println("The instance variable value, "+ "object first, a: "+first.getA()); first.a=2; System.out.println("The instance variable value, "+ "object first, a: "+first.getA()); first.setA(3); System.out.println("The instance variable value, "+ "object first, a: "+first.getA()); }}

Page 45: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 45

run:A constructor called.The instance variable value, object first, a: 1The instance variable value, object first, a: 2The instance variable value, object first, a: 3BUILD SUCCESSFUL (total time: 0 seconds)

Page 46: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 46

• As a second step an object is created to the derived class:

Page 47: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 47

public class Test{ public static void main(String[] args) { B first=new B(1, 2); System.out.println("The instance variable values, object first, a and b: "+ first.getA()+" and "+first.getB()+"."); first.getInfo(); first.a=3; first.b=4; first.getInfo(); }}

Page 48: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 48

A constructor called.B constructor called.The instance variable values, object first, a and b: 1 and 2.The instance variable values a and b are: 1 and 2.The instance variable values a and b are: 3 and 4.BUILD SUCCESSFUL (total time: 0 seconds)

Page 49: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 49

• From the preceding example: using keyword public means that “everything” is possible!

• When a member of a class is modified by the public access specifier, that member can be accessed by any other code in your program wherever the program has a reference to an object of that class or one of its derived classes.

• A small modification to the previous example: base class instance variable access modifier is changed to private:

Page 50: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 50

package TimoSoft;

public class A{ private int a; public A(int aVal) { System.out.println("A constructor called."); setA(aVal); } public void setA(int aValue) { a=aValue; } public int getA() { return a; }}

Page 51: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 51

package TimoSoft;

public class B extends A{ public int b; public B(int aVal, int bVal) { super(aVal); System.out.println("B constructor called."); setB(bVal); } public void setB(int bValue) { b=bValue; } public int getB() { return b; }

Page 52: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 52

public void getInfo() { System.out.println("The instance variable values a and b are: "+ a+" and "+b+"."); }}

This is not allowed: instance variable a does have privateaccess specifier in class A!

Page 53: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 53

public class Test{ public static void main(String[] args) {

A first=new A(1); System.out.println("The instance variable value, "+ "object first, a: "+first.getA()); //first.a=2; first.setA(3); System.out.println("The instance variable value, "+ "object first, a: "+first.getA()); }}

run:A constructor called.The instance variable value, object first, a: 1The instance variable value, object first, a: 3BUILD SUCCESSFUL (total time: 0 seconds)

Page 54: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 54

• From the preceding example: it was possible to modify the instance variable a value because there was a method in the same class, namely public void setA(int aValue).

• So a derived class does not inherit the private members of its base class. However, if the base class has public or protected methods for accessing its private fields, these can also be used by the derived class.

• From the preceding example: let’s create an object to the derived class:

Page 55: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 55

package TimoSoft;

public class Test{ public static void main(String[] args) { B first=new B(1, 2); System.out.println("The instance variable values, "+ "object first, a and b: "+first.getA()+" and "+first.getB()+"."); first.setA(3); first.b=4; System.out.println("The instance variable values, "+ "object first, a and b: "+first.getA()+" and "+first.getB()+"."); }}

Page 56: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 56

run:A constructor called.B constructor called.The instance variable values, object first, a and b: 1 and 2.The instance variable values, object first, a and b: 3 and 4.BUILD SUCCESSFUL (total time: 0 seconds)

Page 57: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 57

• From the preceding example: the object first in the derived class inherited one private instance variable a from the base class.

• It was possible to modify the private instance variable a because there was a method in that same class, namely public void setA(int aValue).

• Using the same logic we used the method public int

getA().

Page 58: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 58

• As a summary:• A class’s public members are accessible whenever the

program has a reference to an object of that class or one of its derived classes.

• A class’s private members are accessible only within the class itself.

• A base class’s private members are not accessible outside the class itself.

• Rather, they are hidden in its derived classes and can be accessed only through the public or protected methods inherited from the base class.

Page 59: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 59

• Using protected access modifier offers an intermediate level of access between public and private.

• A base class’s protected members can be accessed by members of that base class and by members of its derived classes.

• All public and protected base class members retain their original access modifier when they become members of the derived class – public members of the base class become public members of the derived class, and protected members of the base class become protected members of the derived class.

Page 60: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 60

• Derived class methods can refer to public and protected members inherited from the base class simply by using the member names.

• When a derived class method overrides an inherited base class method, the base class method can be accessed from the derived class by preceding the base class method name with keyword super and a dot (.) separator.

• Overridden members of the base class will be discussed later.

Page 61: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 61

• Methods of a derived class cannot directly access private members of their base class. A derived class can change the state of private base class instance variables only through non-private methods provided in the base class and inherited by the derived class.

• Next example covers the situation where there is a protected base class instance variable:

Page 62: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 62

package TimoSoft;

public class A{ protected int a; public A(int aVal) { System.out.println("A constructor called."); setA(aVal); } public void setA(int aValue) { a=aValue; } public int getA() { return a; }}

Page 63: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 63

package TimoSoft;

public class B extends A{ public int b; public B(int aVal, int bVal) { super(aVal); System.out.println("B constructor called."); setB(bVal); } public void setB(int bValue) { b=bValue; } public int getB() { return b; }

Page 64: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 64

public void getInfo() { System.out.println("The instance variable values a and b are: "+ a+" and "+b+"."); }}

This is now allowed: instance variable a does have protected access specifier in class A.

Page 65: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 65

package TimoSoft;

public class Test{ public static void main(String[] args) { B first=new B(1, 2); System.out.println("The instance variable values, "+ "object first, a and b: "+first.getA()+" and "+first.getB()+"."); first.getInfo(); first.a=3; first.b=4; first.getInfo(); }}

run:A constructor called.B constructor called.The instance variable values, object first, a and b: 1 and 2.The instance variable values a and b are: 1 and 2.The instance variable values a and b are: 3 and 4.BUILD SUCCESSFUL (total time: 0 seconds)

Page 66: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 66

• Next modification: one level of class hierarchy has been added:

Page 67: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 67

package TimoSoft;

public class A{ protected int a; public A(int aVal) { System.out.println("A constructor called."); setA(aVal); } public void setA(int aValue) { a=aValue; } public int getA() { return a; }}

Page 68: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 68

package TimoSoft;

public class B extends A{ protected int b; public B(int aVal, int bVal) { super(aVal); System.out.println("B constructor called."); setB(bVal); } public void setB(int bValue) { b=bValue; } public int getB() { return b; }

Page 69: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 69

public void getInfo() { System.out.println("The instance variable values a and b are: "+ a+" and "+b+"."); }}

Page 70: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 70

package TimoSoft;

public class C extends B{ protected int c; public C(int aVal, int bVal, int cVal) { super(aVal, bVal); System.out.println("C constructor called."); setC(cVal); } public void setC(int cValue) { c=cValue; } public int getC() { return c; }

Page 71: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 71

public void getInfo() { System.out.println("The instance variable values "+ "a, b and c are: "+a+", "+b+" and "+c+"."); }}

Overridden instance method public void getInfo().

Page 72: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 72

package TimoSoft;

public class Test{ public static void main(String[] args) { C first=new C(1, 2, 3); System.out.println("The instance variable values "+ "a, b and c are: "+first.getA()+", "+first.getB()+ " and "+first.getC()+"."); first.getInfo(); first.a=4; first.b=5; first.c=6; first.getInfo();

}}

Page 73: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 73

run:A constructor called.B constructor called.C constructor called.The instance variable values a, b and c are: 1, 2 and 3.The instance variable values a, b and c are: 1, 2 and 3.The instance variable values a, b and c are: 4, 5 and 6.BUILD SUCCESSFUL (total time: 1 second)

Page 74: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 74

• The preceding example illustrates one good point:• Instantiating a derived class object begins a chain of

constructor calls in which the derived class constructor, before performing its own tasks, invokes its direct base class’s constructor either explicitly via the super reference or implicitly calling the base class’s default constructor or no-argument constructor. Similarly, if the base class is derived from another class – as is, of course, every class except Object – the base class constructor invokes the constructor of the next class up the hierarchy, and so on.

• The last constructor called in the chain is always the constructor for the class Object.

Page 75: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 75

• The original derived class constructor’s body finishes executing last.

• Each base class’s constructor manipulates the base class instance variables that the derived class object inherits.

• The preceding example served also another important topic: overriding a base class instance method.

• You can define a method in a derived class that has the same signature as a method in the base class.

• The access specifier attribute for the method in the derived class can be the same as that in the base class or less restrictive, but it cannot be more restrictive.

Page 76: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 76

• This means that if you declare a method as public in the base class, for example, any derived class definition of the method must also be declared as public.

• You cannot omit the access specifier attribute in the derived class in this case, or specify it as private or protected.

• When you define a new version of a base class method in this way, the derived class method will be called for a derived class object, not the method inherited from the base class.

• The method in the derived class overrides the method in the base class.

Page 77: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 77

• The base class method is still there though, and it is still possible to call it in a derived class by using the keyword super.

• The ability of a derived class to override a method allows a class to inherit from a base class whose behavior is “close enough” and then to modify behavior as needed.

• The overriding method has the same name, number and type of parameters, and return type as the method it overrides. An overriding method can also return a subtype of the type returned by the overridden method.

Page 78: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 78

• What about overriding a class (static) method? • If a derived class defines a class method with the same

signature as a class method in the base class, the method in the derived class hides the one in the base class. So we do not override base class methods.

Page 79: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 79

• Sometimes it is useful to declare classes – called abstract classes – for which you never intend to create objects.

• Because they are used only as base classes in inheritance hierarchies, we refer to them as abstract base classes.

• These classes cannot be used to instantiate objects, because abstract classes are incomplete.

• Derived classes must declare the “missing pieces” to become concrete classes, from which you can instantiate objects. Otherwise, these derived classes, too, will be abstract.

Page 80: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 80

• An abstract class’s purpose is to provide an appropriate base class from which other classes can inherit and thus share a common design.

• In the Shape hierarchy of Figure 3, for example, derived classes inherit the notion of what it means to be a Shape – perhaps common attributes such as location and color, and behaviors such as draw() and resize().

• Classes that can be used to instantiate objects are called concrete classes. Such classes provide implementations of every method they declare (some of the implementations can be inherited).

• For example we could derive concrete classes Circle, Square and Triangle from abstract base class Shape:

Page 81: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 81

Shape

TriangleSquareCircle

Figure 3. Inheritance hierarchy for the abstract class Shape.

Page 82: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 82

• Abstract base classes are too general to create real objects – they specify only what is common among subclasses.

• Not all hierarchies contain abstract classes. However, programmers often write client code that uses only abstract base class types to reduce client code’s dependencies on a range of derived class types.

• Abstract classes sometimes constitute several levels of a hierarchy. For example, the Shape hierarchy of Figure 3 begins with abstract class Shape. On the next level of the hierarchy can be abstract classes TwoDimensionalShape and ThreeDimensionalShape. The next level of hierarchy declare concrete classes, Figure 4:

Page 83: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 83

Shape

Circle

TwoDimensionalShape ThreeDimensionalShape

Square

Triangle Sphere

Cube

Tetrahedron

Figure 4. Three level inheritance hierarchy for the abstract class Shape.

Page 84: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 84

• You make a class abstract by declaring it with keyword abstract.

• An abstract class normally contains one or more abstract methods.

• An abstract method is one with keyword abstract in its declaration (without braces), as in:

public abstract void calculateArea();

• Abstract methods do not provide implementations.• A class that contains any abstract methods must be

explicitly declared as an abstract class even if that class contains some non-abstract methods.

Page 85: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 85

• Each concrete derived class of an abstract base class must provide concrete implementations of each of the base class’s abstract methods.

• However, if it does not, the derived class must also be declared abstract.

• Constructors and static methods cannot be declared abstract.

• Constructors are not inherited, so an abstract constructor could never be implemented.

• Though non-private static methods are inherited, they cannot be overridden. Since abstract methods are meant to be overridden so that they can process objects based on their types, it would not make sense to declare a static method as abstract.

Page 86: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 86

• The instance variables and concrete methods of an abstract class are subject to the normal rules of inheritance.

• If an abstract class contains only abstract method declarations, it should be declared as an interface instead.

• Interfaces will be discussed later.• Abstract classes are most commonly extended to share

pieces of implementation.• A single abstract class is extended by similar derived

classes that have a lot in common (the implemented parts of the abstract base class), but also have some differences (the abstract methods).

Page 87: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 87

package Timosoft;

public abstract class GraphicObject{ protected int x, y; public void moveTo() { System.out.println("This has been implemented “+

“in the abstract base class."); } public void setXValue(int xVal) { x=xVal; } public void setYValue(int yVal) { y=yVal; }

Page 88: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 88

int getXValue() { return x; } int getYValue() { return y; } public abstract void draw(); public abstract void resize();}

Page 89: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 89

package Timosoft;

public class Rectangle extends GraphicObject{ public Rectangle(int xValue, int yValue) { this.setXValue(xValue); this.setYValue(yValue); } public void draw() { System.out.println("Draw the Rectangle class object."); }

Page 90: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 90

public void resize() { System.out.println("Resize the Rectangle class object."); } public void whereToStart() { System.out.println("Drawing starts from the xy-coordinate value pair ("+ this.getXValue()+", "+this.getYValue()+")."); }}

Page 91: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 91

package Timosoft;

public class Test{ public static void main(String[] args) { Rectangle first=new Rectangle(3, -5); first.draw(); first.whereToStart(); first.moveTo(); first.resize(); }}

run:Draw the Rectangle class object.Drawing starts from the xy-coordinate value pair (3, -5).This has been implemented in the abstract base class.Resize the Rectangle class object.BUILD SUCCESSFUL (total time: 1 second)

Page 92: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 92

• It is also possible to implement a constructor to the abstract base class:

Page 93: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 93

package Timosoft;

public abstract class GraphicObject{ protected int x, y; public GraphicObject(int xValue, int yValue) { System.out.println("Abstract base class constructor called."); setXValue(xValue); setYValue(yValue); } public void moveTo() { System.out.println("This has been implemented “+

“in the abstract base class."); } public void setXValue(int xVal) { x=xVal; }

Page 94: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 94

public void setYValue(int yVal) { y=yVal; } int getXValue() { return x; } int getYValue() { return y; } public abstract void draw(); public abstract void resize();}

Page 95: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 95

package Timosoft;

public class Rectangle extends GraphicObject{ public Rectangle(int xVa, int yVa) { super(xVa, yVa); System.out.println("Rectangle derived class constructor called."); } public void draw() { System.out.println("Draw the Rectangle class object."); }

Page 96: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 96

public void resize() { System.out.println("Resize the Rectangle class object."); } public void whereToStart() { System.out.println("Drawing starts from the xy-coordinate value pair ("+ this.getXValue()+", "+this.getYValue()+")."); }}

Page 97: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 97

package Timosoft;

public class Test{ public static void main(String[] args) { Rectangle first=new Rectangle(3, -5); first.draw(); first.whereToStart(); first.moveTo(); first.resize(); }}

run:Abstract base class constructor called.Rectangle derived class constructor called.Draw the Rectangle class object.Drawing starts from the xy-coordinate value pair (3, -5).This has been implemented in the abstract base class.Resize the Rectangle class object.BUILD SUCCESSFUL (total time: 4 seconds)

Page 98: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 98

• Which one is better? To implement a constructor to abstract base class or to just implement the needed mutator methods to abstract base class?

• Constructor implementation is better!• Maybe there is a need to overload your abstract base

class constructor!• If you only used mutator methods, you would need to

duplicate the calls to them in every single derived class constructor!

Page 99: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 99

• If you choose not to implement a constructor to the abstract base class, it would still have the default (system provided) parameterless constructor which in turn would call the default constructor from the Object class!!!

• So I would write my own constructor to abstract base class…

Page 100: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 100

• You can declare some or all of a class’s methods final.

• You use the final keyword in a method declaration to indicate that the method cannot be overridden by derived classes:

public final void calculateArea();

• You might wish to make a method final if it has an implementation that should not be changed and it is critical to the consistent state of the object.

Page 101: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 101

• Methods called from constructors should generally be declared final.

• If a constructor calls a non-final method, a derived class may redefine that method with surprising or undesirable results.

• Note that you can also declare an entire class final – this prevents the class from being inherited.

• This is particularly useful, for example, when creating an immutable class like the String class:

public final class String

extends Object

Page 102: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 102

• A class can have references to objects of other classes as members.

• This is called composition and is sometimes referred to as a has-a-relationship.

• For example, an AlarmClock object needs to know the current time and the time when it’s supposed to sound its alarm, so it’s reasonable to include two references to Time objects in an AlarmClock object.

• In the next example there is class Date and class Student. Class Student has instance variable birthDate which is a reference to Date object:

Page 103: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 103

package TimoSoft;

public class Date{ protected int day; protected int month; protected int year;

public Date(int theDay, int theMonth, int theYear) { setDay(theDay); setMonth(theMonth); setYear(theYear); } void setDay(int dVal) { day=dVal; }

Page 104: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 104

void setMonth(int mVal) { month=mVal; } void setYear(int yVal) { year=yVal; }}

Page 105: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 105

package TimoSoft;

public class Student{ protected String firstName; protected String secondName; protected Date birthDate;

public Student(String first, String second, Date dateOfBirth) { setFirstName(first); setSecondName(second); setBirthDate(dateOfBirth); } void setFirstName(String firstVal) { firstName=firstVal; }

Page 106: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 106

void setSecondName(String secondVal) { secondName=secondVal; } void setBirthDate(Date birthVal) { birthDate=birthVal; } void getInfo() { System.out.println("Student's name is "+ this.firstName+" "+this.secondName+ " and the birthday party will be held on "+ this.birthDate.day+"."+this.birthDate.month+ "."+this.birthDate.year+"."); }}

Page 107: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 107

package TimoSoft;

public class Test { public static void main(String[] args) { Date birth=new Date(4, 2, 2010); Student stud=new Student("Joe", "Blow",birth); stud.getInfo(); }}

run:Student's name is Joe Blow and the birthday party will be held on 4.2.2010.BUILD SUCCESSFUL (total time: 1 second)

Page 108: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 108

• Class Test creates Date object birth. Then Student object stud is created and during that process Date object birth initializes stud’s instance variable birthDate.

• In the UML diagram the solid diamond attached to the Student class’s association line indicate that the Student class has a composition relationship with the class Date.

• Composition implies a whole/part relationship.• The class that has the composition symbol (the solid

diamond) on its end of the association line is the whole, and the class on the other end of the association line is part:

Page 109: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 109

Date Student

Figure 5. Class diagram showing composition relationship.

Page 110: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 110

• Composition relationships have the following properties:

1. Only one class in the relationship can represent the whole (i.e., the diamond can be placed on only one end of the association line).

2. The parts in the composition relationship exist only as long as the whole does, and the whole is responsible for the creation and destruction of its parts.

3. A part may belong to only one whole at a time, although it may be removed and attached to another whole, which then assumes responsibility for the part.

Page 111: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 111

• If a has-a-relationship does not satisfy one or more of these criteria, the UML specifies that hollow diamonds be attached to the ends of association lines to indicate aggregation – a weaker form of composition.

• For example, a personal computer and a computer monitor participate in an aggregation relationship. The computer has a monitor, but the two parts can exist independently, and the same monitor can be attached to multiple computers at once, thus violating composition’s second and third properties.

Page 112: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 112

• One more visit to the preceding example. The method void getInfo() seems a bit complex and error prone.

• Let’s try to use the method toString():

public String toString()

• toString() is one of the methods that every class inherits directly or indirectly from class Object.

• Method toString() returns a String representing an object.

Page 113: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 113

• It’s called implicitly whenever an object must be converted to a String representation, such as when an object is output by printf or String method format using the %s format specifier.

• Class Object’s toString() method returns a String that includes the name of the object’s class.

• It’s primarily a placeholder that can be overridden by a derived class to specify an appropriate String representation of the data in a derived class object.

• To override a base class method, a derived class must declare a method with the same signature as the base class method – Object’s toString() method takes no parameters:

Page 114: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 114

package TimoSoft;

public class Date{ protected int day; protected int month; protected int year;

public Date(int theDay, int theMonth, int theYear) { setDay(theDay); setMonth(theMonth); setYear(theYear); } public void setDay(int dVal) { day=dVal; }

Page 115: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 115

public void setMonth(int mVal) { month=mVal; } public void setYear(int yVal) { year=yVal; } @Override public String toString() { return String.format("%d.%d.%d", day, month, year); }}

Page 116: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 116

package TimoSoft;

public class Student{ protected String firstName; protected String secondName; protected Date birthDate;

public Student(String first, String second, Date dateOfBirth) { setFirstName(first); setSecondName(second); setBirthDate(dateOfBirth); } public void setFirstName(String firstVal) { firstName=firstVal; }

Page 117: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 117

public void setSecondName(String secondVal) { secondName=secondVal; } public void setBirthDate(Date birthVal) { birthDate=birthVal; } @Override public String toString() { return String.format("Student's name is: %s %s\nThe birthday “+

“party will be held on: %s", firstName, secondName, birthDate); }}

Page 118: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 118

package TimoSoft;

public class Test {

public static void main(String[] args) { Date birth=new Date(4, 2, 2010); Student stud=new Student("Joe", "Blow",birth); System.out.println(stud); }}

run:Student's name is: Joe BlowThe birthday party will be held on: 4.2.2010BUILD SUCCESSFUL (total time: 0 seconds)

Page 119: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 119

• @Override annotation indicates, that method toString() should override a base class method.

• Annotations have several purposes.• For example, when you attempt to override a base class

method, common errors include naming the derived class method incorrectly, or using the wrong number or types of parameters in the parameter list.

• Each of these problems creates an unintentional overload of the base class method.

• If you then attempt to call the method on a derived class object, the base class’s version is invoked and the derived class version is ignored – potentially leading to subtle logic errors.

Page 120: InheritancetMyn1 Inheritance Inheritance is a form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing

Inheritance tMyn 120

• When the compiler encounters a method declared with @Override, it compares the method’s signature with the base class’s method signatures.

• If there is not an exact match, the compiler issues an error message, such as “method does not override or implement a method from a supertype”.

• This indicates that you have accidentally overloaded a base class method.