Unit II-INHERITANCE

Introduction: • inheritance is that we can create new classes that are built on existing classes. • When we inherit from an existing class, we reuse (or inherit) its methods and fields and we add new methods and fields to adapt our new class to new situations. • Classes, Super classes, and Subclasses • Consider our previous example program employee class. • Manager will be treated differently in a company, they may have common feature with employee.

• What way they differed, employee may directly get the salary from company. • But manager may take additionally bonus with their salary. • most of employee features are taken by manager • When we are going to put manager aspects to the existing program(Employee), we may take this as a new class derived from employee class. • “is–a” relationship between Manager and Employee. • Every manager is an employee: • “is–a” relationship is the hallmark of inheritance.

• Define a Manager class that inherits from the Employee class. • Java keyword extends to denote inheritance. • class Manager extends Employee • { • added methods and fields • } • keyword extends indicates that you are making a new class that derives from an existing class. • The existing class is called the superclass, base class, or parent class. • The new class is called the subclass, derived class, or child class.

• if you have an Employee object, you cannot apply the setBonus method—it is not among the methods that are defined in the Employee class. • We can use methods such as getName with Manager objects. • Even though this method are not explicitly defined in the Manager class, they are automatically inherited from the Employee super class. • Similarly, the fields name, salary are inherited from the super class. • Every Manager object has three fields: name, salary and bonus.

• DESIGN CONSIDERATION • When defining a subclass by extending its super class, we only need to indicate the differences between the subclass and the super class. • When designing classes, we place the most general methods into the super class and more specialized methods in the subclass. • some of the superclass methods are not appropriate for the Manager subclass. • In particular, the getSalary method should return the sum of the base salary and the bonus. • we need to supply a new method to override the super class method:

• • • • •

Method coding will be, public double getSalary() { return salary + bonus; // won't work } The getSalary method of the Manager class has no direct access to the private fields of the superclass. • This means that the getSalary method of the Manager class cannot directly access the salary field, even though every Manager object has a field called salary. • Only the methods of the Employee class have access to the private fields. • if the Manager methods want to access those private fields, they have to do what every other method does—use the public interface, in this case, the public getSalary method of the Employee class.

• call the getSalary method of the Employee superclass, not the current class. • we use the special keyword super for this purpose. The call • super.getSalary() • calls the getSalary method of the Employee class. • public double getSalary() • { • double baseSalary = super.getSalary(); • return baseSalary + bonus; }

• • • • • •

let us supply a constructor, public Manager(String n, double s ) { super(n, s); bonus = 0; } Here super keyword calls its super class constructor with the arguments of name and salary. • If the subclass constructor does not call a superclass constructor explicitly, then the default (no-parameter) constructor of the superclass is invoked. • If the super class has no default constructor and the subclass constructor does not call another super class constructor explicitly, then the Java compiler reports an error.

• fact that an object variable (such as the variable e) can refer to multiple actual types is called polymorphism. • Automatically selecting the appropriate method at runtime is called dynamic binding.

Inheritance Hierarchies collection of all classes extending from a common superclass is called an inheritance hierarchy. The path from a particular class to its ancestors in the inheritance hierarchy is its inheritance chain.

• Polymorphism
• “Is – a “ relationship states that every object of the subclass is an object of the superclass. • Every manager is an employee. • Opposite is not true- not every employee is a manager. • “Is –a “ rule states substitution principle. • It states that we can use a subclass object whenever the program expects a superclass object. • Employee e; • e = new Employee(. . .); // Employee object • expected • e = new Manager(. . .); // OK, Manager can be • used as well

• object variables are polymorphic • A variable of type Employee can refer to an object of type Employee or to an object of any subclass of the Employee class. • Manager boss = new Manager(. . .); • Employee[] staff = new Employee[3]; • staff[0] = boss; • In this case, the variables staff[0] and boss refer to the same object.

• • • • •

That means, we can call boss.setBonus(5000); // OK but we can’t call staff[0].setBonus(5000); // ERROR The declared type of staff[0] is Employee, and the setBonus method is not a method of the Employee class. • Because staff[0] is considered to be only an Employee object by the compiler. • Next cannot assign a superclass reference to a subclass variable. For example,

• Dynamic Binding • to understand what happens when a method call is applied to an object. • 1. The compiler looks at the declared type of the object and the method name. • Let’s say we call x.f(param), and the implicit parameter x is declared to be an object of class C.

• The compiler enumerates all methods called f in the class C and all public methods called f in the super classes of C. • 2. the compiler determines the types of the parameters that are supplied in the method call. • If among all the methods called f there is a unique method whose parameter types are a best match for the supplied parameters, then that method is chosen to be called. This process is called overloading resolution. • compiler reports an error if more than one functions are matched or no parameter match.

• 3. If the method is private, static, final, or a constructor, then the compiler knows exactly which method to call. This is called static binding. • 4. When the program runs and uses dynamic binding to call a method, then the virtual machine must call the version of the method that is appropriate for the actual type of the object to which x refers. • Let’s say the actual type is D, a subclass of C. If the class D defines a method f(String), that method is called.

• If not, D’s superclass is searched for a method f(String), and so on. • It would be time consuming to carry out this search every time a method is called • virtual machine precomputes for each class a method table that lists all method signatures and the actual methods to be called. • When a method is actually called, the virtual machine simply makes a table lookup

• At runtime, the call e.getSalary() is resolved as follows: • 1. First, the virtual machine fetches the method table for the actual type of e. That may be the table for Employee, Manager, or another subclass of Employee. • 2. Then, the virtual machine looks up the defining class for the getSalary() signature. • Now it knows which method to call. • 3. Finally, the virtual machine calls the method.

• Dynamic binding has a very important property: it makes programs extensible without the need for modifying existing code. • Suppose a new class Executive is added and there is the possibility that the variable e refers to an object of that class. • The code containing the call e.getSalary() need not be recompiled. • The Executive.getSalary() method is called automatically if e happens to refer to an object of type Executive.

• Preventing Inheritance: Final Classes and Methods • Classes that cannot be extended are called final classes, and you use the final modifier in the definition of the class to indicate this. • let us suppose we • want to prevent others from subclassing the Executive class. Then, we simply declare the • class by using the final modifier as follows: • final class Executive extends Manager • { ... }

• You can also make a specific method in a class final. If you do this, then no subclass can • override that method. (All methods in a final class are automatically final.) For example: • class Employee • { • ... • public final String getName() • { • return name; • } ... }

• reason to make a method or class final: to make sure that the semantics cannot be changed in a subclass. • For example, the getTime and setTime methods of the Calendar class are final. • If a method is not overridden, and it is short, then a compiler can optimize the method call away—a process called inlining. • Casting • Needed if we want to assign superclass object reference to subclass object.

• • • • • • • •

Manager boss = (Manager) staff[1]; // ERROR if (staff[1] instanceof Manager) { boss = (Manager) staff[1]; ... } Rules: we can cast only within an inheritance hierarchy. • Use instanceof to check before casting from a superclass to a subclass.

• Abstract Classes
• move up the inheritance hierarchy, classes become more general and probably more abstract. • Consider, for example, an extension of our Employee class hierarchy. • An employee is a person, and so is a student. • Let us extend our class hierarchy to include classes Person and Student.

• There are some attributes that make sense for every person, such as the name. • Both students and employees have names, so introducing a common getName method to a higher level in the inheritance hierarchy. • Student class have a field of major and employee class have the field of salary. • add another method, getDescription, whose purpose is to return a brief description of the person, such as • an employee with a salary of $50,000.00 • a student majoring in computer science • easy to implement this method for the Employee and Student classes. • But what information can we provide in the Person class? The Person class knows nothing about the person except the name. • We can make a method in the person class with empty string. • Otherwise we will make a method as abstract by using abstract keyword.

• public abstract String getDescription(); • // no implementation required • a class with one or more abstract methods must itself be declared abstract. • In addition to abstract methods, abstract classes can have fields and concrete methods. • For example, the Person class stores the name of the person and has a concrete method that returns it.
• • • • • • abstract class Person { public Person(String n) { name = n; }

• • • • • • • • • • • •

public abstract String getDescription(); public String getName() { return name; } private String name; } A class can even be declared as abstract even though it has no abstract methods. Abstract classes cannot be instantiated. That is, if a class is declared as abstract, no objects of that class can be created. For example, the expression new Person("Vince Vu") is an error.

• However, we can create objects of concrete subclasses. • Note that you can still create object variables of an abstract class, but such a variable must refer to an object of a nonabstract subclass. • For example: • Person p = new Student("Vince Vu", "Economics"); • Here p is a variable of the abstract type Person that refers to an instance of the nonabstract subclass Student. • Let us define a concrete subclass Student that extends the abstract Person class: • class Student extends Person • { • public Student(String n, String m) • { • super(n); • major = m; • }

• The Student class defines the getDescription method. • Therefore, all methods in the Student class are concrete, and the class is no longer an abstract class. • Similarly the employee class is to be extended by person class. It is also a concrete class.

Protected Access 1. Visible to the class only (private). 2. Visible to the world (public). 3. Visible to the package and all subclasses (protected). • 4. Visible to the package—the (unfortunate) default. No modifiers are needed.

• Object: The Cosmic Superclass
• The Object class is the ultimate ancestor—every class in Java extends Object. • However, we never have to write class Employee extends Object • we can use a variable of type Object to refer to objects of any type: • Object obj = new Employee("Harry Hacker", 35000); • We may cast object type to any specific type, • Employee e = (Employee) obj; • In Java, only the primitive types (numbers, characters, and boolean values) are not objects. • All array types, no matter whether they are arrays of objects or arrays of primitive types, are class types that extend the Object class.

• • • • • •

•
• • • • •

Employee[] staff = new Employee[10]; obj = staff; // OK obj = new int[10]; // OK The equals Method The equals method in the Object class tests whether one object is considered equal to another. The equals method, as implemented in the Object class, determines whether two object references are identical For example, let us consider two employees equal if they have the same name, salary. class Employee { ... public boolean equals(Object otherObject) { // a quick test to see if the objects are identical if (this == otherObject) return true;

• When we define the equals method for a subclass, first call equals on the superclass. • If that test doesn’t pass, then the objects can’t be equal. • If the superclass fields are equal, then we will compare the subclass objects, • class Manager extends Employee • { ... • public boolean equals(Object otherObject) • { • if (!super.equals(otherObject)) return false;

• 2. It is symmetric: For any references x and y, x.equals(y) should return true if and only if y.equals(x) returns true. • 3. It is transitive: For any references x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true. • 4. It is consistent: If the objects to which x and y refer haven’t changed, then repeated calls to x.equals(y) return the same value. • 5. For any non-null reference x, x.equals(null) should return false.

• Arrays API • static boolean equals(type[] a, type[] b) • returns true if the arrays have equal lengths and equal elements in corresponding positions. • The hashCode Method • A hash code is an integer that is derived from an object. • Hash codes should be scrambled—if x and y are two distinct objects, there should be a high probability that x.hashCode() and y.hashCode() are different.

• System.out.println(t.hashCode() + " " + tb.hashCode()); • Note that the strings s and t have the same hash code because, for strings, the hash codes are derived from their contents. • The string builders sb and tb have different hash codes because no hashCode method has been defined for the StringBuilder class, and the default hashCode method in the Object class derives the hash code from the object’s memory address.

• For example, here is a hashCode method for the Employee class: • class Employee • { • public int hashCode() • { • return 7 * name.hashCode() • + 11 * new Double(salary).hashCode(); • } • ... } • Definitions of equals and hashCode must be compatible: if x.equals(y) is true, then x.hashCode() must be the same value as y.hashCode().

• The toString Method
• Another important method in Object is the toString method that returns a string representing the value of this object. • toString methods follow this format: the name of the class, followed by • the field values enclosed in square brackets. Here is an implementation of the toString • method for the Employee class: • public String toString() • { • return "Employee[name=" + name • + ",salary=" + salary • + "]"; • }

• whenever an object is concatenated with a string by the “+” operator, the Java compiler automatically invokes the toString method to obtain a string representation of the object. For example: • Point p = new Point(10, 20); • String message = "The current position is " + p; • // automatically invokes p.toString()