Академический Документы
Профессиональный Документы
Культура Документы
JAVA INHERITANCE
Laboratory No. 4
Objectives
Learn when to use inheritance. Learn how to use the super keyword. Learn how to override methods.
Background
In Java, all classes, including the classes that make up the Java API, are subclassed rom the Object superclass. A sample class hierarchy is shown below. Any class above a speci ic class in the class hierarchy is known as a superclass. !hile any class below a speci ic class in the class hierarchy is known as a subclass o that class. Inheritance is a ma"or advantage in ob"ect#oriented programming since once a behavior $method% is de ined in a superclass, that behavior is automatically inherited by all subclasses. &hus, you can encode a method only once and they can be used by all subclasses. A subclass only need to implement the di erences between itsel and the parent.
public class Person { protected String name; protected String address; /** * Default constructor */ public Person(){ System.out.println(Inside Person:Constructor); name = ""; address = "";
Computer Programming 2 2
} /** * Constructor with 2 parameters */ public Person( String name, String address ){ this.name = name; this.address = address; } /** * Accessor methods */ public String getName(){ return name; } public String getAddress(){ return address; } public void setName( String name ){ this.name = name; } public void setAddress( String add ){ this.address = add; } }
Notice that, the attributes name and address are declared as protected. &he reason we did this is that, we want these attributes to be accessible by the subclasses o the superclass. I we declare this as private, the subclasses won't be able to use them. &ake note that all the properties o a superclass that are declared as public$ protected and de!ault can be accessed by its subclasses. Now, we want to create another class named (tudent. (ince a student is also a person, we decide to "ust e)tend the class Person, so that we can inherit all the properties and methods o the e)isting class Person. &o do this, we write,
public class Student extends Person { public Student(){ System.out.println(Inside Student:Constructor); //some code here } // some code here }
!hen a (tudent ob"ect is instantiated, the de ault constructor o its superclass is invoked implicitly to do the necessary initiali*ations. A ter that, the statements inside the subclass are e)ecuted. &o illustrate this, consider the ollowing code,
public static void main( String[] args ){ Student anna = new Student();
Computer Programming 2 3
In the code, we create an ob"ect o class (tudent. &he output o the program is,
Computer Programming 2 4
&his code calls the second constructor o its immediate superclass $which is Person% and e)ecutes it. Another sample code shown below,
&his code calls the de ault constructor o its immediate superclass $which is Person% and e)ecutes it. &here are a ew things to remember when using the super constructor call.. &he super$% call /0(& 12203 &45 +I3(& (&A&5/5N& IN A 21N(&302&13. 6. &he super$% call can only be used in a constructor de inition. 7. &his implies that the this$% construct and the super$% calls 2ANN1& 81&4 12203 IN &45 (A/5 21N(&302&13. Another use o super is to re er to members o the superclass $"ust like the t%is re erence %. +or e)ample,
Overriding (et%ods
I or some reason a derived class needs to have a di erent implementation o a certain method rom that o the superclass, overriding methods could prove to be very use ul. A subclass can override a method de ined in its superclass by providing a new implementation or that method. (uppose we have the ollowing implementation or the getName method in the Person superclass,
public class Person { : : public String getName(){ System.out.println("Parent: getName"); return name; }
Computer Programming 2 5
: }
public class Student extends Person { : : public String getName(){ System.out.println("Student: getName"); return name; } : }
(o, when we invoke the getName method o an ob"ect o class (tudent, the overridden method would be called, and the output would be, (tudent- getName
/any o the classes in the Java API are declared inal to ensure that their behavior cannot be overridden. 5)amples o these classes are Integer, 9ouble and (tring. It is also possible in Java to create methods that cannot be overridden. &hese methods are what we call !inal *et%ods. &o declare a method to be inal, we "ust add the inal keyword in the method declaration. +or e)ample, i we want the getName method in class Person to be declared inal, we write,
Computer Programming 2 6
(tatic methods are automatically inal. &his means that you cannot override them.
Computer Programming 2 7
Instruction. Choose the best answer. Encircle your answer. 1. What type of inheritance does Java have? a. single inheritance b. double inheritance c. multiple inheritance d. class inheritance 2. Say that there are three classes: Computer, AppleComputer, and IBMComputer. What are the likely relationships between these classes? a. Computer is the superclass, AppleComputer and IBMComputer are subclasses of Computer. b. IBMComputer is the superclass, AppleComputer and Computer are subclasses of IBMComputer. c. Computer is a superclass, AppleComputer is a subclasses of Computer, and IBMComputer is a subclass of AppleComputer Computer, AppleComputer and IBMComputer are sibling classes. 3. Can an object be a subclass of another object? a. Yesas long as single inheritance is followed. b. Noinheritance is only between classes. c. Only when one has been defined in terms of the other. d. Yeswhen one object is used in the constructor of another. 4. How many objects of a given class can there be in a program? a. One per defined class. b. One per constructor definition. c. As many as the program needs. d. One per main() method 5. What restriction is there on using the super reference in a constructor? a. It can only be used in the parent's constructor. b. Only one child class can use it. c. It must be used in the last statement of the constructor. d. It must be used in the first statement of the constructor 6. Which of the following is correct syntax for defining a new class Jolt based on the superclass SoftDrink? a. class Jolt isa SoftDrink { //additional definitions go here } b. class Jolt implements SoftDrink { //additional definitions go here } c. class Jolt defines SoftDrink { //additional definitions go here } d. class Jolt extends SoftDrink { //additional definitions go here } 7. A class Car and its subclass Yugo both have a method run() which was written by the programmer as part of the class definition. If junker refers to an object of type Yugo, what will the following code do? junker.show(); a. The show() method defined in Yugo will be called. b. The show() method defined in Car will be called. c. The compiler will complain that run() has been defined twice. d. Overloading will be used to pick which run() is called. 8. A class Animal has a subclass Mammal. Which of the following is true: a. Because of single inheritance, Mammal can have no subclasses. b. Because of single inheritance, Mammal can have no other parent than Animal. c. Because of single inheritance, Animal can have only one subclass. d. Because of single inheritance, Mammal can have no siblings. 9. Does a subclass inherit both member variables and methods? a. Noonly member variables are inherited.
Computer Programming 2 8
b. Noonly methods are inherited. c. Yesboth are inherited. d. Yesbut only one or the other are inherited 10. Which of the following is NOT an advantage to using inheritance? a. Code that is shared between classes needs to be written only once. b. Similar classes can be made to behave consistently. c. Enhancements to a base class will automatically be applied to derived classes.
Computer Programming 2 9
>
Now, here's a sample code of a class that uses our Exercie1 class.
public class Main { public static void main(String[] args) { Student ako = new Student(); }//main
}// class
Now, add this one in your /ain class a ter your instantiation.
System.out.println("name: "+ako.getName()); System.out.println("address: "+ako.getAddress());
0pdate your (tudent class, add this code in the irst line in your student constructor.
super$<berns<, <baguio city<%=
3un your program and e)amine the output. 0pdate your (tudent class, add this code in the irst line in your student constructor. 2omment out the this line- super$<berns<, <baguio city<%=
super.name;<mark<= super.address;<vigan<=
3un your program and e)amine the output. 0pdate your (tudent class, override the getName method by adding this segment o code.
public (tring getName$%: return$<this is a value that is returned by this method<%=
}
3un your program and e)amine the output.
public class Dog { protected String name; public Dog(){ } public Dog(String name) { this.name = name; } public String getName() { return name; } public String speak() { return "Woof"; } }// Dog
A class derived rom 9og that holds in ormation about a labrador retriever. 1verrides 9og speak method and includes in ormation about avg weight or this breed.
public class Labrador extends Dog { private String color; //black, yellow, or chocolate? private int breedWeight = 75; public Labrador(String name, String color) { this.color = color; } public String speak() { return "WOOF"; } public static int avgBreedWeight() { return breedWeight; } }//Labrador
A class derived rom 9og that holds in ormation about a ?orkshire terrier. 1verrides 9og speak method.
public class Yorkshire extends Dog { public Yorkshire(String name) { super(name); } public String speak() { return "woof"; } }// Yorkshire
A simple test class that creates a 9og and makes it speak.
public class Main { public static void main(String[] args){ Dog dog = new Dog("Spike"); System.out.println(dog.getName() + " says " + dog.speak()); } } File Dog.java contains a declaration for a Dog class. Save this file to your directory and study itnotice what instance
variables and methods are provided. +iles Labrador.java and Yorkshire.java contain declarations or classes that e)tend 9og. (ave and study these iles as well. +ile Main.java contains a simple driver program that creates a dog and makes it speak. (tudy Main.java, save it to your directory, and compile and run it to see what it does. Now modi y these iles as ollows.. Add statements in Main.java a ter you create and print the dog to create and print a ?orkshire and a Labrador. Note that the Labrador constructor takes two parameters- the name and color o the labrador, both strings. 9on't change any iles besides Main.java. Now recompile Main.java= you should get an error saying something like
b. +i) the problem $which really is in Labrador% so that Main.java creates and makes the 9og, Labrador, and ?orkshire all speak. 6. Add code to Main.java to print the average breed weight or both your Labrador and your ?orkshire. 0se the avg8reed!eight$% method or both. !hat error do you get@ !hy@ ;A
+i) the problem by adding the needed code to the ?orkshire class.