Yosemite National Park, California CSE 114 Computer Science I Inheritance
Containment A class contains another class if it instantiates an object of that class HAS-A also called aggregation PairOfDice HAS-A Die
Inheritance One class can be derived from another class inherits its instance variables and methods child class -----> parent class IS-A subclass class derived class base class Any instance variable or method that is inherited by a subclass does not need to be redefined in the subclass.
Why use Inheritance? Customize classes (from the JDK or your own) Benefits: Don t have to re-write code Abstraction the JDK has many classes to customize, especially for GUIs Use methods and variables of fully tested classes Code in super classes can be used by a limitless number of subclasses Making changes to common properties is easier just change the parent class
Inheritance is powerful And the real reason? Why? Code written today can call methods written 10 years from now Huh? That s due to inheritance & polymorphism, more on this next lecture
Inheritance Syntax public class ChildClass extends ParentClass { // instance variables for Child only // methods for Child only ChildClass now contains all instance variables and methods defined above, as well as those defined inside ParentClass
How to organize classes using Inheritance Determine what data you need to store. For example, for storing student and employee data: Student data: name, age, GPA Employee data: name, age, salary Divide up your classes according to state since Students and Employees store different data, use separate classes Pool common data into a common parent class Person data: name, age Have Student and Employee classes customize Person
Example: Parent Class: Person public class Person { private String name; private int age; // constructor public Person(String initname) { age = 0; // just born name = initname; // accessor method public String getname() { return name; // accessor method public int getage() { return age; // mutator method public void setage(int newage) { if (newage < 0) age = 0; else age = newage;
Example: Child (Sub-)Class: Student public class Student extends Person { private double gpa; // constructor for a Student public Student(String initname) { super(initname); gpa = 0.0; Means Student inherits all instance variables and methods from Person Runs Person s constructor public double getgpa() { return gpa; public void setgpa(double newgpa) { if (newgpa < 0.0 newgpa > 4.0) gpa = 0.0; else gpa = newgpa;
Example: Child (Sub-)Class: Employee public class Employee extends Person { private int salary; // constructor for an Employee public Employee(String initname) { super(initname); salary = 0; public int getsalary() { return salary; public void setsalary(int newsalary) { if (newsalary < 0 newsalary > 400000) salary = 0; else salary = newsalary;
How much memory do they need? When we construct a Student? age: 4 bytes name: 4 bytes for String memory address more memory for String data itself of course gpa: 8 bytes How about an Employee? age: 4 bytes name: 4 bytes for String memory address salary: 4 bytes
Example: Using all three classes public class PeopleTester { public static void main(string[] args) { Person moe = new Person("Moe Stooge"); Student larry = new Student("Larry Stooge"); Employee curly = new Employee("Curly Stooge"); moe.setage(106); moe.setgpa(2.2); moe.setsalary(100000); // LEGAL? // LEGAL? // LEGAL? YES! NO! NO! larry.setage(101); larry.setgpa(1.2); larry.setsalary(50000); // LEGAL? // LEGAL? // LEGAL? YES! YES! NO! curly.setage(100); curly.setgpa(0.5); curly.setsalary(25000); // LEGAL? // LEGAL? // LEGAL? NO! YES! YES!
Inheritance: public vs. private Inherited methods are accessible by the derived class if they are public or protected. Inherited instance variables are not directly accessible by the derived class if they are private. Use public accessor/mutator methods of parent class instead. For example, if we added a clear method inside Student: public void clear() { age = 0; gpa = 0.0; ILLEGAL public void clear() { setage(0); gpa = 0.0; LEGAL private methods of a base class are not accessible by the derived class.
Inheritance: super() and this() super() runs base (parent) class' constructor Must be first statement in a derived class' constructor If it is left out, super() is still executed using the base class' default constructor (with no parameters) this() runs a class' own constructor Used on first line of another constructor May pass parameters to this() as long as they correspond to parameters for another constructor For example, if we added a new constructor for Student: public Student(String initname, double initgpa) { this(initname); gpa = initgpa; Runs the previously defined Student constructor
Inheritance: Overriding Methods A method is overridden if it is redefined in a derived class (child class) using the same method Signature. Person (parent class): public void reset() { age = 0; Student (child class): public void reset() { setage(0); gpa = 0.0; OR, Calling an overridden method: public void reset() { super.reset(); gpa = 0.0; What happens if you forget super?
Method Summary protected Object The Object class Every class is a subclass of the java.lang.object class, even if not specified directly. clone() Creates and returns a copy of this object. boolean equals(object obj) Indicates whether some other object is "equal to" this one. String tostring() Returns a string representation of the object. Automatically Called on an object whenever it is placed inside System.out.print( The 3 methods above are overridden nearly every time a new class is defined. The Object class also contains 8 other methods we won t use
Overriding tostring() method Example public class Person { public String tostring() { return name + ", age " + age; public class Student extends Person { public String tostring() { return super.tostring() + ", GPA: " + gpa; public class Employee extends Person { public String tostring() { return super.tostring() + ", Salary: $" + salary;
Printing using tostring() public class StoogePrinter { public static void main(string[] args) { Person moe = new Person("Moe Stooge"); Student larry = new Student("Larry Stooge"); Employee curly = new Employee("Curly Stooge"); System.out.println(moe.toString()); System.out.println(larry.toString()); System.out.println(curly); OUTPUT: Moe Stooge, age 0 Larry Stooge, age 0, GPA: 0.0 Curly Stooge, age 0, Salary: $0
public class Course { public int coursenumber = 114; public class Classroom { public String building = "Javits"; public int roomnumber = 100; public String tostring() { return building + roomnumber; Exercise to try at home public class LectureHall extends Classroom { public int capacity = 650; public class ToStringExample { public static void main(string[] args) { System.out.println(new Course()); System.out.println(new Classroom()); System.out.println(new LectureHall()); What output do you get?
Multiple Inheritance A class may extend only 1 class, however, when it does so it also inherits all methods and variables that the parent class has already inherited Example: public class Instructor extends Employee { private String dept; public Instructor(String initname) { super(initname); dept = "None Assigned"; public String getdept() { return dept; public void setdept(string newdept) { dept = newdept; public String tostring() { return super.tostring() + ", Dept: " + dept; public static void main(string[] args) { Instructor me = new Instructor("Richard McKenna"); System.out.println(me); OUTPUT: Richard McKenna, age 0, Salary: $0, Dept: None Assigned
Inheritance Diagrams Think of an inheritance diagram as a family tree for classes, except for a couple of differences: A class may only have 1 immediate parent No criss-crossing in a class tree Every class has all the properties (state and behavior) of all of it s ancestors (so much for Darwinism) Student Person Employee Instructor A class may have any number of ancestors, in this case Instructor has 2.
Inheritance Diagrams family tree? The Town Drunk Mama Uncle Ernie Mary Joe Joe Bob Farmer s daughter across state line Old Man Up the Mountain Elvira Fat Irma Little Bob Cletus Mary Joe Elvis Selma Sue Danger: The family tree is crossing!
Inheritance Diagram Example Object Component A class may only have 1 immediate parent No criss-crossing in a class tree Container JComponent Window JPanel AbstractButton Frame JButton JFrame
Interfaces An interface is a collection of abstract methods that are defined by all classes that implement it. cannot be instantiated includes headers for the methods but no implementation generally used to force a class to implement certain methods public interface Clock { public void set(int hour, int minute); public String gettime(); public class Watch implements Clock { // CLASS DEFINITION FOR Watch GOES HERE // MUST define public methods set() and gettime()