Вы находитесь на странице: 1из 12

Computer Programming 2 1

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.

e!ining "uperclasses and "ubclasses


&o derive a class, we use the e#tends keyword. In order to illustrate this, let's create a sample parent class. (uppose we have a parent class called Person.

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,

Inside Person:Constructor Inside Student:Constructor

&he program low is shown below.

T%e super ke&'ord


A subclass can also e#plicitl& call a constructor o its immediate superclass. &his is done by using the super constructor call. A super constructor call in the constructor o a subclass will result in the e)ecution o relevant constructor rom the superclass, based on the arguments passed. +or e)ample, given our previous e)ample classes Person and (tudent, we show an e)ample o a super constructor call. ,iven the ollowing code or (tudent,

public Student(){ super( "SomeName", "SomeAddress" ); System.out.println("Inside Student:Constructor");

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,

public Student(){ super(); System.out.println("Inside Student:Constructor"); }

&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,

public Student() { super.name = somename; super.address = some address; }

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

: }

&o override, the getName method in the subclass (tudent, we write,

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

)inal (et%ods and )inal Classes


In Java, it is also possible to declare classes that can no longer be subclassed. &hese classes are called !inal classes. &o declare a class to be inal, we "ust add the inal keyword in the class declaration. +or e)ample, i we want the class Person to be declared inal, we write,

public final class Person { //some code here }

/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,

public final String getName(){ return name; }

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

(odule + In%eritance E#ercise , + "tudent Record -rogra*


5ncode this programpublic class Person : protected (tring name;<<= protected (tring address;<<= public Person$%: (ystem.out.println$<this is the contructor o the class person<%= > public Person$(tring name, (tring address%: this.name;name= this.address;address= > public (tring getName$%: return$name%= > public (tring getAddress$%: return$address%= > public void setName$(tring name%: this.name;name= > public void setAddress$(tring address%: this.address;address= > > 5ncode this programpublic class (tudent e)tends Person : public (tudent$%: (ystem.out.println$<this is the contructor o the class student<%= >

>

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

Computer Programming 210

}// class

3un the program and e)amine the output.

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.

Computer Programming 211

(odule +Object Oriented -rogra**ing E#ercise . + og

A class that holds a dog's name and can make it speak.

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.

Computer Programming 212

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

null says WOOF


a. !hat's going on@ $4int- !hat call must be made in the constructor o a subclass@% ;A

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.

Вам также может понравиться