Now that we understand the power of creating objects and invoking the methods that belong to each object, we can explore the notion of inheritance. In real life, we understand by inheritance as “something that we receive from an old/previous generation”. Some examples of inheritance can be:
Money/Land
Features in our face
Values
debt
Personality
Genetics
Diseases
In Java, we use the power of inheritance from an ancestor called Object. As we described in previous section, in Java we inherited 11 methods from this class (this including the .toString() and .equals()).
One the features why inheritance was introduced in programming, was to incorporate the notion of reusability. Since we already spend an enormous amount of time designing a specific object, might as well re-use it in different form.
The inheritance relationship that is established in java is called the is-a relationship. This means that the objects that we define are a sub-form of a super object as follows:
The relationship allows us to identify the hierarchy of what object belongs to other objects. In programming, the class Object is the root of all objects, also called the super class. We will keep with the same example of Dollar, being the super class, and now with a new object called CanadianDollar, to be the subclass.
The setup that allows a class to inherit attributes to the super class is by using the keyword extends after the definition of the class. This allows to communicate with the super class Dollar and inherit the fields, and methods and allows to communicate with constructors to initialize the fields.
public class CanadianDollar extends Dollar{
}
In addition, we need to add the remaining fields that are not part of Dollar, however, they are needed in CanadianDollar. In our case, it is only color, and it should be represented as a String.
String color;
All fields in java, since they represent the uniqueness of the object, should be private. We will introduce another encapsulation type called protected. The protected type is useful in the inheritance stage since we are creating objects that communicate with other objects that share the same fields or methods.
protected String color;
and in a UML diagram is denoted with the symbol “#” (if you are old school, we called this symbol pound if you are new school, you may call it hashtag).
Let us define a customize constructor that takes the same number of parameters as the number of fields that we have in Dollar, i.e., int denomination, String face, String serial, int year, String color.
The way we communicate the subclass with the super class, is through the keyword super. The keyword super must be used as the first line in the constructor to call the super class constructor. So it looks as follows:
This means that we will call in our super calls Dollar a customized constructor that takes four parameters in the order of int, String, String, and int.
public CanadianDollar(int denomination, String face, String serial, int year, String color){
super(denomination, face, serial, year);
this.color = color;
}
Let us save the CanadianDollar under the same directory where Dollar is saved
In the tester, i.e., DepOfTreasury, we will incorporate the following Canadian Dollars as part of our inventory of Dollars.
CanadianDollar c1 = new CanadianDollar(5,"Laurier", "C123456D", 2000,"blue");
CanadianDollar c2 = new CanadianDollar(10,"Macdonald","C789456D",1999,"purple");
CanadianDollar c3 = new CanadianDollar(20,"ElizabethII","C212121D", 1998,"green");
System.out.println(c1);
By compiling and running the above code, we expect the hexadecimal address location when we attempt to print the object c1, however, we obtained:
$5 Face: Laurier #C123456D Y:2000 and is 17 years old!
Since CanadianDollar extends the class Dollar, we inherited the toString() method from Dollar.
Notice that the Canadian dollar has two attributes in addition to the regular Dollar object.
It has a ‘C’ before the $ sign, and
It has a color.
It will be nice to have textual representation under CanadianDollar that provided us with these attributes. We can make that happen by overwriting the toString() method inherited from Dollar.
In the class CanadianDollar, we can incorporate the following method.
public String toString(){
return “C”+super.toString()+color;
}
By running the same program from the tester, we got the following for c1
C$5 Face: Laurier #C123456D Y:2000 and is 17 years old! Color: blue
If we use the Javadoc to visualize the information in the class CanadianDollar, we have
Notice that the toString() now appears under the method for CanadianDollar, and it was removed from Dollar.
Occasionally, we can prevent overwriting for future methods. The way to avoid method-overwriting is by incorporating the modifier final in the method. For example,
public final String toString(){
String s = "$"+denomination+" Face: "+face+" #"+serial+" Y:"+year+" and is "+getAge()+" years old!";
return s;
}
When we attempt to run this program; we will have the following syntax error at CanadianDollar
1 error found:
File: C:\...\CanadianDollar.java [line: 11]
Error: toString() in CanadianDollar cannot override toString() in Dollar
overridden method is final
AP CS A
[Using Methods]
MOD-3.B Create an inheritance relationship from a subclass to the superclass.
MOD-3.B.1 A class hierarchy can be developed by putting common attributes and behaviors of related classes into a single class called a superclass.
MOD-3.B.2 Classes that extend a superclass, called subclasses, can draw upon the existing attributes and behaviors of the superclass without repeating these in the code.
MOD-3.B.3 Extending a subclass from a superclass creates an “is-a” relationship from the subclass to the superclass.
MOD-3.B.4 The keyword extends is used to establish an inheritance relationship between a subclass and a superclass. A class can extend only one superclass.
MOD-3.C.3 If S is a subclass of T, then a reference of type T can be used to refer to an object of type T or S.
MOD-3.C.4 Declaring references of type T, when S is a subclass of T, is useful in the following declarations— ● Formal method parameters ● arrays — T[] var ArrayList<T> var.
MOD-3.D Call methods in an inheritance relationship.
MOD-3.D.1 Utilize the Object class through inheritance.
MOD-3.D.2 At compile time, methods in or inherited by the declared type determine the correctness of a non-static method call.
MOD-3.D.3 At run-time, the method in the actual object type is executed for a non-static method call.
MOD-3.E Call Object class methods through inheritance.
MOD-3.E.1 The Object class is the superclass of all other classes in Java.
MOD-3.E.4 Subclasses of an Object often override the equals and toString methods in class-specific implementations
MOD-3.E.2 The Object class is part of the java.lang package.
MOD-3.E.3 The following Object class methods and constructors—including what they do and when they are used—are part of the Java Quick Reference— ● boolean equals(Object other) ● boolean equals(Object other)
[Superclass Constructor and Methods]
MOD-3.B.5 Constructors are not inherited.
MOD-3.B.6 The superclass constructor can be called from the first line of a subclass constructor by using the keyword super and passing appropriate parameters.
MOD-3.B.7 The actual parameters passed in the call to the superclass constructor provide values that the constructor can use to initialize the object’s instance variables.
MOD-3.B.8 When a subclass’s constructor does not explicitly call a superclass’s constructor using super, Java inserts a call to the superclass’s no-argument constructor.
MOD-3.B.9 Regardless of whether the superclass constructor is called implicitly or explicitly, the process of calling superclass constructors continues until the Object constructor is called. At this point, all of the constructors within the hierarchy execute beginning with the Object constructor.
MOD-3.B.10 Method overriding occurs when a public method in a subclass has the same method signature as a public method in the superclass.
MOD-3.B.11 Any method that is called must be defined within its own class or its superclass.
MOD-3.B.12 A subclass is usually designed to have modified (overridden) or additional methods or instance variables.
MOD-3.B.13 A subclass will inherit all public methods from the superclass; these methods remain public in the subclass.
MOD-3.B.14 The keyword super can be used to call a superclass’s constructors and methods.
MOD-3.B.15 The superclass method can be called in a subclass by using the keyword super with the method name and passing appropriate parameters.
MOD-3.C Define reference variables of a superclass to be assigned to an object of a subclass in the same hierarchy.
MOD-3.C.1 When a class S “is-a” class T, T is referred to as a superclass, and S is referred to as a subclass.
MOD-3.C.2 If S is a subclass of T, then assigning an object of type S to a reference of type T facilitates polymorphism.
[Random Numbers]
CON-1.D.4 The values returned from Math.random can be manipulated to produce a random int or double in a defined range
[Documentation Comments]
MOD-2.C.3 A precondition is a condition that must be true just prior to the execution of a section of program code in order for the method to behave as expected. There is no expectation that the method will check to ensure preconditions are satisfied.
MOD-2.C.4 A postcondition is a condition that must always be true after the execution of a section of program code. Postconditions describe the outcome of the execution in terms of what is being returned or the state of an object.
MOD-2.C.5 Programmers write method code to satisfy the postconditions when preconditions are met.
Explain the importance of algorithms in the problem-solving process.
Demonstrate how a problem may be solved by multiple algorithms, each with different properties.
Read a given program, and explain what it does
Trace the flow of control during the execution of a program (both correct and incorrect).
Use appropriate terminology to identity elements of a program (e.g., identifier, operator, operand)
Reading and explaining code
Basic concepts such as variables, primitive data types, expression evaluation, assignment, etc.
Apply basic programming style guidelines to aid readability of programs such as comments, indentation, proper naming of variables, etc.
Basic testing (perhaps using suitable frameworks) including test case design
Basic concepts such as variables, primitive data types, expression evaluation, assignment, etc.
Key modularity constructs such as functions (and methods and classes, if supported in the language) and related concepts like parameter passing, scope, abstraction, data encapsulation, etc.
When and how to use standard data structures
Structured data types available in the chosen programming language like sequences (e.g., arrays, lists), associative containers (e.g., dictionaries, maps), others (e.g., sets, tuples) and when and how to use them.