java inheritance

12
1 Computer Programming 2 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 from the Object superclass. A sample class hierarchy is shown below. Any class above a specific class in the class hierarchy is known as a superclass. While any class below a specific class in the class hierarchy is known as a subclass of that class. Inheritance is a major advantage in object-oriented programming since once a behavior (method) is defined in a superclass, that behavior is automatically inherited by all subclasses. Thus, you can encode a method only once and they can be used by all subclasses. A subclass only need to implement the differences between itself and the parent. Defining Superclasses and Subclasses To derive a class, we use the extends keyword. In order to illustrate this, let's create a sample parent class. Suppose 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 = "";

Upload: estevao-paquete

Post on 19-Oct-2015

74 views

Category:

Documents


5 download

TRANSCRIPT

  • 1

    Computer Programming 2

    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 from the

    Object superclass. A sample class hierarchy is shown below.

    Any class above a specific class in the class hierarchy is known as a superclass. While any class

    below a specific class in the class hierarchy is known as a subclass of that class.

    Inheritance is a major advantage in object-oriented programming since once a behavior (method)

    is defined in a superclass, that behavior is automatically inherited by all subclasses. Thus, you can

    encode a method only once and they can be used by all subclasses. A subclass only need to

    implement the differences between itself and the parent.

    Defining Superclasses and Subclasses

    To derive a class, we use the extends keyword. In order to illustrate this, let's create a sample

    parent class. Suppose 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 = "";

  • 2

    Computer Programming 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. The reason we did this is

    that, we want these attributes to be accessible by the subclasses of the superclass. If we declare

    this as private, the subclasses won't be able to use them. Take note that all the properties of a

    superclass that are declared as public, protected and default can be accessed by its subclasses.

    Now, we want to create another class named Student. Since a student is also a person, we decide

    to just extend the class Person, so that we can inherit all the properties and methods of the

    existing class Person. To do this, we write,

    public class Student extends Person { public Student(){ System.out.println(Inside Student:Constructor); //some code here }

    // some code here }

    When a Student object is instantiated, the default constructor of its superclass is invoked implicitly

    to do the necessary initializations. After that, the statements inside the subclass are executed. To

    illustrate this, consider the following code,

    public static void main( String[] args ){ Student anna = new Student();

  • 3

    Computer Programming 2

    }

    In the code, we create an object of class Student. The output of the program is,

    Inside Person:Constructor Inside Student:Constructor

    The program flow is shown below.

    The super keyword

    A subclass can also explicitly call a constructor of its immediate superclass. This is done by using

    the super constructor call. A super constructor call in the constructor of a subclass will result in the

    execution of relevant constructor from the superclass, based on the arguments passed.

    For example, given our previous example classes Person and Student, we show an example of a

    super constructor call. Given the following code for Student,

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

  • 4

    Computer Programming 2

    }

    This code calls the second constructor of its immediate superclass (which is Person) and executes

    it. Another sample code shown below,

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

    This code calls the default constructor of its immediate superclass (which is Person) and executes

    it.

    There are a few things to remember when using the super constructor call:

    1. The super() call MUST OCCUR THE FIRST STATEMENT IN A CONSTRUCTOR.

    2. The super() call can only be used in a constructor definition.

    3. This implies that the this() construct and the super() calls CANNOT BOTH OCCUR IN THE

    SAME CONSTRUCTOR.

    Another use of super is to refer to members of the superclass (just like the this reference ). For

    example,

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

    Overriding Methods

    If for some reason a derived class needs to have a different implementation of a certain method

    from that of the superclass, overriding methods could prove to be very useful. A subclass can

    override a method defined in its superclass by providing a new implementation for that method.

    Suppose we have the following implementation for the getName method in the Person superclass,

    public class Person { :

    :

    public String getName(){ System.out.println("Parent: getName"); return name; }

  • 5

    Computer Programming 2

    :

    }

    To override, the getName method in the subclass Student, we write,

    public class Student extends Person { :

    :

    public String getName(){ System.out.println("Student: getName"); return name; } :

    }

    So, when we invoke the getName method of an object of class Student, the overridden method

    would be called, and the output would be,

    Student: getName

    Final Methods and Final Classes

    In Java, it is also possible to declare classes that can no longer be subclassed. These classes are

    called final classes. To declare a class to be final, we just add the final keyword in the class

    declaration. For example, if we want the class Person to be declared final, we write,

    public final class Person { //some code here }

    Many of the classes in the Java API are declared final to ensure that their behavior cannot be

    overridden. Examples of these classes are Integer, Double and String.

    It is also possible in Java to create methods that cannot be overridden. These methods are what

    we call final methods. To declare a method to be final, we just add the final keyword in the

    method declaration. For example, if we want the getName method in class Person to be declared

    final, we write,

    public final String getName(){ return name; }

  • 6

    Computer Programming 2

    Static methods are automatically final. This means that you cannot override them.

  • 7

    Computer Programming 2

    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.

  • 8

    Computer Programming 2

    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.

  • 9

    Computer Programming 2

    Module : Inheritance Exercise 1 : Student Record Program

    Encode this program:

    public class Person {

    protected String name=""; protected String address="";

    public Person(){

    System.out.println("this is the contructor of the class person"); }

    public Person(String name, String address){ this.name=name;

    this.address=address; }

    public String getName(){

    return(name);

    }

    public String getAddress(){ return(address);

    }

    public void setName(String name){

    this.name=name;

    }

    public void setAddress(String address){

    this.address=address; }

    }

    Encode this program:

    public class Student extends Person {

    public Student(){

    System.out.println("this is the contructor of 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

  • 10

    Computer Programming 2

    }// class

    Run the program and examine the output.

    Now, add this one in your Main class after your instantiation.

    System.out.println("name: "+ako.getName());

    System.out.println("address: "+ako.getAddress()); Update your Student class, add this code in the first line in your student constructor.

    super("berns", "baguio city");

    Run your program and examine the output.

    Update your Student class, add this code in the first line in your student constructor.

    Comment out the this line: super("berns", "baguio city");

    super.name="mark"; super.address="vigan";

    Run your program and examine the output. Update your Student class, override the getName method by adding this segment of code.

    public String getName(){

    return("this is a value that is returned by this method");

    }

    Run your program and examine the output.

  • 11

    Computer Programming 2

    Module :Object Oriented Programming Exercise 2 : Dog

    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 from Dog that holds information about a labrador retriever. Overrides Dog speak method and includes information about avg weight for 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 from Dog that holds information about a Yorkshire terrier. Overrides Dog 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 Dog and makes it speak.

  • 12

    Computer Programming 2

    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. Files Labrador.java and Yorkshire.java contain declarations for classes

    that extend Dog. Save and study these files as well.

    File Main.java contains a simple driver program that creates a dog and makes it speak. Study Main.java, save

    it to your directory, and compile and run it to see what it does. Now modify these files as follows:

    1. Add statements in Main.java after you create and print the dog to create and print a Yorkshire and a Labrador. Note that the Labrador constructor takes two parameters: the name and color of the

    labrador, both strings. Don't change any files besides Main.java. Now recompile Main.java; you should get an error saying something like

    null says WOOF

    a. What's going on? (Hint: What call must be made in the constructor of a subclass?)

    =>

    b. Fix the problem (which really is in Labrador) so that Main.java creates and makes the Dog,

    Labrador, and Yorkshire all speak.

    2. Add code to Main.java to print the average breed weight for both your Labrador and your Yorkshire.

    Use the avgBreedWeight() method for both. What error do you get? Why?

    =>

    Fix the problem by adding the needed code to the Yorkshire class.