180 likes | 194 Views
Object-Oriented Programming Design Topic : Inheritance. Maj Joel Young Joel.Young@afit.edu. Inheritance. Definition -- a class (the derived class) inherits from another class (the base class) if the derived class describes a specialized subset of those objects characterized by the base class
E N D
Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming DesignTopic : Inheritance Maj Joel Young Joel.Young@afit.edu
Inheritance • Definition -- a class (the derived class) inherits from another class (the base class) if the derived class describes a specialized subset of those objects characterized by the base class • Any object of the derived class must be usable in place of a base class object • Depicts an "is-a" relationship • Terminology • Existing class called superclass, base class, or parent class • New class called subclass, derived class, or child class • Characteristics • Reuse or change existing methods • Add new instance fields or methods • Subclasses have more functionality than their superclasses • Unless otherwise specified, subclass uses methods of superclass • Only the differences need to be specified in subclass • Thus superclass factors out common methods and instance fields
Inheritance • Inheritance may extend more than one level • Inheritance hierarchy -- collection of classes extending from common parent • Inheritance chain -- path from a particular class to its ancestors • Inheritance right for your program if any object of the subclass can be used in place of the superclass object. Subclass objects are usable in any code that uses the superclass. • Implementation in Java class Derived extends Base { . . . } • Reference super class– super
Inheritance Hierarchy Person {abstract} -Name +Breathe() Employee Student {abstract} -AreaOfStudy +Pay() +Study() Staff Faculty -PayRate -Salary +Pay() +Pay()
Inheritance • Operations in Base and Derived classes • Consider derived class D, and operation f() of base class B • Derived class can inherit function f() without change • Derived class can replace f() with its own f() with different behavior • Derived class can extend f() with its own f() that calls the base version of f() and performs other tasks class Manager extends Employee { . . . public double getSalary() { double baseSalary = super.getSalary(); return baseSalary + bonus; } . . . }
Polymorphism • An object's ability to decide which method (with the same name) to apply to itself depending on where it is in the inheritance hierarchy. • When message asks a subclass to apply a method using certain parameters: • Subclass checks if it has method with same name and parameter types (i.e. same signature) • If no method in subclass, then Java looks in the parent class for matching method • This extends up the inheritance chain until a matching method is found or there are no more superclasses (in which case an exception is raised) • Method in subclass with same name and parameters as method in an ancestor class hides method of ancestor class.
Dynamic Binding • Because of inheritance, it may be possible that more than one version of a method with the same name is available to be executed. In Java the actual object itself is inspected to determine the correct method to execute. This run-time decision is called dynamic binding. In C++, these kinds of methods are called virtual functions. Unlike Java, C++ virtual functions must be explicitly declared to use dynamic binding through the virtual keyword. • The next slide shows an example with the printName() method in Person and Engineer.
Polymorphism Person Course 1..* -Name: String -Num: Integer +printName() +printRoll() Engineer -Specialty: String +printName()
class Engineer extends Person { String m_specialty; public Engineer(String name, String specialty) { super(name); m_specialty = specialty; } public void printName() { System.out.print(m_name+": "+m_specialty); } } class Example { static public void main(String args[]) { // Create a course Course c = new Course(); // Add students Person p = new Person(“Joe”); c.addPerson(p); // Alternate way to add objects c.addPerson(new Person(“Sue”)); c.addPerson(new Engineer(“Bob”,”EE”)); // Print the roll c.printRoll(); } } Output: Joe Sue Bob: EE Polymorphism
Preventing inheritance • Final classes and methods • final class MyString { … } • MyNewString.java:23: Can’t subclass final classes: class MyString • class MyString { … final void printme() { … } … } • Why? • Security … prevent coders from overriding your expected behavior by inheriting from your class or from overriding certain methods. Enforced in bitecode • Design … one should design for inheritance. If you believe that nobody has any business inheriting from your class, make it final. You won’t get that call saying: “You changed your class in this new release and I inherited from you and now I’m XXXXed” • Efficiency … final methods can be inlined which means the compiler puts the bitecode right at the call saving the cost of making a call
Casting • Converting from one class to another • Can only be done within inheritance hierarchy. • Explicit cast necessary when going from superclass (with less functionality) to subclass (with more functionality). • You should be sure superclass can be cast to the subclass; otherwise information will be lost. • Should only be done when you want to use an object in its full capacity after its type has been downplayed. • Check whether object is instance of another object before casting it - instanceof if ( staff[1] instanceof Manager ) { boss = (Manager) staff[1]; …… }
Abstract classes • Class used as a framework for other classes • No instances of abstract class • Useful for organizing common classes and factoring out common methods • Class with one or more abstract methods must be declared as abstract class. • Abstract class may also contain methods that are not abstract public abstract class Message { . . . public abstract void play(); public String getSender() { return sender; } private String sender; }
Abstract Classes Person {abstract} -Name +getDescription() Employee Student {abstract} -AreaOfStudy +getDescription() +getDescription() abstract class Person { public Person(String n) { name = n; } public abstract String getDescription(); public String getName() { return name; } private String name; }
class Employee extends Person { public Employee(String n, double s) { super(n); salary = s; } . . . public String getDescription() { . . . return “Employee with a salary of “ + formatter.format(salary); } private double salary; } class Student extends Person { public Student(String n, String m) { super(n); major = m; } public String getDescription() { return "a student majoring in " + major; } private String major; } Abstract Classes
The Object Superclass • Ancestor of every class in Java • Provides a number of default methods, for example • equals • clone • toString • Makes it easier to create generic classes (templates)
Java API Tools • Object wrappers • Wrappers for primitive types (e.g. int, long, float) • Allow primitive types to be used as objects • All wrapper classes are final, so derived classes can't change them • Can then be used in generic classes that require Object class • Examples • Integer • Double • Java HTML Documentation • Inheritance tree • Class name, access modifiers, class interfaces, parent class, and class description • Method index • Method description • Can be generated with javadoc command and /** … */ comments
Design Hints for Inheritance • Common operations and fields belong in the superclass • Use inheritance to model the "is-a" relationship • Don't use inheritance unless all inherited methods make sense • Example of why not -- Holiday derived from Day class -- what about method advance • Use polymorphism, not type information • E.g. use inheritance mechanisms (dynamic method dispatch) to differentiate between different methods among different types of subclasses
Homework • Read about Integer, Double, BigInteger, BigDecimal • How do you do math on Integer and Double instances? • Just what is the purpose of Integer and Double? When would you use them in your code? You will answer this in class… • COMACC Calculator Question and Answer Session • Analysis etc. still due Monday. Email it to me (no hard copy) joel.young@afit.edu