Download presentation
Presentation is loading. Please wait.
1
Inheritance Recitation - 02/22/2008 CS 180 Department of Computer Science, Purdue University
2
Announcements Project 3 grades are out. Collect at the end of the recitation. Project 5 has been posted. 2-week project. Milestone due 27 th Feb. Final submission due 5 th March. You are seriously recommended to start it early. A reminder regarding the course policy for CS180 - A first instance of academic dishonesty will result in a zero for that assignment plus a letter grade deduction at the end of the semester.
3
Introduction to Inheritance Inheritance allows us to define a general class and then define more specialized classes simply by adding new details to the more general class definition. A more specialized class inherits the properties of the more general class, so that only new features need to be programmed. An inherit class (or a sub-class) can inherit properties from more than one super-class.
4
Introduction to Inheritance, cont. Example General class Vehicle might have instance variables for weight and maximum occupancy. More specialized class Automobile might add instance variables for wheels, engine size, and license plate number. General class Vehicle might also be used to define more specialized classes Boat and Airplane.
5
Programming Example: A Base Class class Person { private String name; public Person() { name = “no name”; } public Person(String _name) { name = _name; } //setName(String) and getName() methods //sameName(String) method //writeOutput() method }
6
Derived Classes Consider a college record-keeping system with records about students, faculty and staff. All these specific groups are sub-classes of the class Person.
7
Derived Classes, cont. Even though your program may not need any Person or Student objects, these classes can be useful for consolidating and representing features common to all subclasses. For example, all students, faculty, and staff have names, and these names may need to be initialized, changed, retrieved, or printed.
8
Derived Classes, cont. class Student is a sub-class of class Person and class Person is called the base class. public class Student extends Person{ private int studentNumber; public Student(String _name, int _num){ super(_name); studentNumber = _num; } //more methods not in Person class //writeOutput() overwrites the method in Person class }
9
Derived Classes, cont. When you define a derived class, you declare only the added instance variables and you define only the added and overridden methods. The variables and methods of the parent class which are not declared private are inherited automatically. Protected variables are available only to classes derived from the class. different than public.
10
Derived Classes, cont. class InheritanceDemo
11
Overriding Method Definitions A particular sub-class might require a specific method already in the base-class to work differently. This calls for overriding that method. Notice that class Student has a method writeOutput(), and class Person also has a method writeOutput() redefined. When a derived class defines a method with the same name and the same number and types of parameters as a method in the base class, the method in the derived class overrides/replaces the method in the base class.
12
Overriding vs. Overloading When you override a method, the new method definition in the derived class has the same name and the same number of types of parameters as the method definition in the base class. Overriding is like replacing the derived method from the super-class by your own. When the name is the same, but the number or types of the parameters (the signature) differs, the method is overloaded.
13
The final Modifier You can prevent a method definition from being overridden by adding the word final to the method heading. example public final void someMethod() { … } The method someMethod() will not be overridden in any sub-class.
14
Constructors in Derived Classes A base class has its own constructors. Their purpose typically is to initialize the instance variables declared in the base class. A derived class has its own constructors Their purpose typically is to call a constructor in the base class, and then to initialize the instance variables declared in the derived class.
15
Using super The call to the constructor in the super class (using the keyword super ) must be the first action taken in the constructor of a sub-class. When no call to the constructor in the super class is included, Java automatically includes a call to the default constructor in the base class. super(initialName); not Person(initialName); //Illegal!!
16
Using super, cont. equivalent definitions: public Student() { super(); studentNumber= 0; } and public Student() { //java automatically includes a call to the //default constructor of the super-class studentNumber= 0; }
17
The this Method Recall that within the definition of one constructor, a call to another constructor in the same class can be made using the this keyword. Example – Student() { this (“Default Name”, 0); } Student(String name, int _num){ ….. }
18
The this Method, cont. Any use of this must be the first action in the constructor definition. Thus, a constructor definition cannot contain a call using super and a call using this. To use both super and this, include a call using this in one constructor and a call using super in the constructor called using this. Example – Student() { this (“Default Name”, 0); } Student(String name, int _num){ super(); ….. }
19
Calling an Overridden Method super can be used to call a method in the base class that has been overridden in the derived class. Example super.writeOutput(); The above line in the Student class would call the overridden writeOutput() method in the Person class. This need not be the first line of code. You cannot use super to invoke a method in some ancestor class other than the immediate base (parent) class.
20
Programming Example: Multilevel Derived Classes Class Undergraduate can be derived from class Student which is derived from class Person. Class Undergraduate will have all the instance variables and methods of class Student which has all the instance variables and methods of class Person. Person Undergraduate Student
21
Programming Example: Multilevel Derived Classes, cont. class Undergraduate extends Student { private int level; public Undergraduate(){ super(); level = 1; } //more methods specific to an undergraduate void writeOutput(){ //override writeOutput() …. }
22
An Object Can Have More than One Type If class Undergraduate is derived from class Student and class Student is derived from class Person, then every object of class Undergraduate is also an object of class Student and an object of class Person. A reference to an object of a sub-class can be substituted for a reference of an ancestor class. However, a reference to an object of an ancestor cannot be substituted for a reference to an object of a derived class.
23
An Object Can Have More than One Type, cont. Given public static void compareNumbers (Student s1, Student s2) then either SomeClass.compareNumbers (studentObject, undergradObject); or SomeClass.compareNumbers (undergradObject, studentObject); could be used. However, SomeClass.compareNumbers (personObject, studentObject); cannot be used.
24
The Class Object In Java, every class descends from (and inherits features from) the Object class. Therefore, every object of every class is of type Object. Unless a class is declared explicitly to be a descendant of some other class, it is an immediate descendant of the class Object. An object of any class can substituted when a parameter of type Object is expected.
25
The Class Object, cont. Every class inherits some methods from the class Object : equals() toString() but usually these methods are overridden by the derived class or by an intermediate ancestor class. Method toString Inherited method toString takes no arguments. Typically, method toString is coded to produce and return a string which contains everything of interest about the object.
26
Abstract Classes An abstract class is not intended to be used to create objects. Abstract method – By declaring one or more methods to be abstract and by omitting the method body, only objects of derived classes which override the method(s) can be instantiated. example public abstract void drawHere(); A class that has at least one abstract method must be declared abstract.
27
Abstract Classes, cont. Public abstract class Figure{ private int offset; public abstract void drawHere(); public void drawAt(int num){ int count; for(count = 0; count < num; count++){ System.out.println(); } drawHere(); }
28
Interfaces An interface specifies the headings for methods that must be defined for any class that implements the interface. Example -
29
Interfaces, cont. A class that implements an interfaces must implement all the methods specified by the interface. To implement an interface, a class must include the phrase implements Interface_Name at the start of the class definition example class CS180 implements Writable {…} implement all the method headings listed in the definition of the interface.
30
Dynamic Binding Different objects can invoke different method definitions using the same method name. For example, if Square and Triangle are sub- classes of the class Figure, and s and t are both objects of type Figure, where s references a Square and t references a Triangle, b and t invoke different definitions of method computeArea()
31
Dynamic Binding, cont. Handling the invocation of a method that may be overridden later is called dynamic binding or late binding. The type of object being referenced at the time of the method call, not the type of reference that was declared, determines which method is invoked. Example – Consider class Student with sub-classes Graduate and UnderGraduate, each with writeOutput() overridden. Student s1 = new Graduate(); Student s2 = new UnderGraduate(); s1.writeOutput() and s2. writeOutput() make calls to two different methods.
32
Type Checking and Dynamic Binding Recall that an object reference to an ancestor class can refer to an object of a descendant class. Student e = new Student(); Person p; p = e; You can invoke only a method in class Person with the variable p. However, if a method is overridden in the class Student, and variable p references an Student object, then the method in class Student is used. The variable determines what methods can be used, but the type referenced by the object determines which definition of the method will be used.
33
Type Checking and Dynamic Binding, cont. To use a method name in the class Student with an object named by the variable p of type Person, use a type cast. Example Student e = (Student)p; e.setStudentNumber(5678);
34
Another Dynamic Binding Example Recall the Person class with sub-classes Student, Graduate, Staff etc. Person[] x = new Person[100]; x[0] = new Student(); x[1] = new Graduate(); x[2] = new Staff();.. How does the compiler decide which method x[i].writeOutput() is calling?
35
Determining Class Type The following are the ways to determine class type of an object. (x instanceof A) – returns true if x is an instance of class A or a subclass of A x.getClass().equals(A.class) – true if x is an instance of class A A.class.isAssignableFrom(x.getClass()) is true if x is an instance of class A or a subclass of A
36
Determining Class Type public class Animal { protected int age; public void makeSound() { SOP(“Make sound!”); } } public class Ferret extends Animal { public Ferret() { super(); } public void eatSweets() { SOP(“Yummy!”); } public void makeSound() { SOP(“Squeal!”); } } public class Platypus extends Animal { public Platypus() { super(); } public void swim() { SOP(“Swim!”); } public void makeSound() { SOP(“Quack!”); } } Animal a = new Ferret(); if (a instanceof Ferret) ((Ferret)a).eatSweets(); a = new Platypus(); if (a.getClass() == Platypus.class) ((Platypus)a).swim(); if (Platypus.class.isAssignableFrom(a)) ((Platypus)a).swim(); ________________________________ Animal a = new Ferret(); ((Platypus)a).swim();// compiles, but runtime error!
37
Subtle Difference Dynamic binding refers to the process carried out by the computer. Polymorphism can be thought of as something objects do. Polymorphism, encapsulation, and inheritance and considered to be the main features of object- oriented programming.
38
Summary You have become acquainted with inheritance. You have learned how to define and use derived classes. You have learned about dynamic binding and polymorphism.
39
Quiz abstract public class Animal {…} abstract public class Bird extends Animal {…} abstract public class Mammal extends Animal {…} abstract public class Fish extends Animal {…} public class Owl extends Bird {…} public class Bat extends Mammal {…} public class Whale extends Mammal {…} public class Shark extends Fish {…} Which instantiations are valid? Animal a = new Animal(); Animal b = new Fish(); Animal c = new Shark(); Mammal d = new Bat(); Fish e = new Mammal(); Bird b = new Owl(); G Given the following declarations, which of the shown instantiations are valid?
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.