Download presentation
Presentation is loading. Please wait.
Published byDwight Chase Modified over 8 years ago
1
CSE 114 – Computer Science I Inheritance Yosemite National Park, California
2
Containment A class contains another class if it instantiates an object of that class –“HAS-A” –also called aggregation PairOfDice HAS-A Die
3
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.
4
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
5
And the real reason? Inheritance is powerful Why? Code written today can call methods written 10 years from now –Huh? That’s due to inheritance & polymorphism, more on this next lecture
6
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
7
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
8
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; }
9
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; } public double getGpa() { return gpa; } public void setGpa(double newGpa) { if (newGpa 4.0) gpa = 0.0; else gpa = newGpa;} } Runs Person ’s constructor Means Student inherits all instance variables and methods from Person
10
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 400000) salary = 0; else salary = newSalary;} }
11
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
12
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);// LEGAL? moe.setGpa(2.2); // LEGAL? moe.setSalary(100000);// LEGAL? larry.setAge(101);// LEGAL? larry.setGpa(1.2);// LEGAL? larry.setSalary(50000); // LEGAL? curly.setAge(100); // LEGAL? curly.setGpa(0.5); // LEGAL? curly.setSalary(25000); // LEGAL? } YES! NO! YES! NO! YES!
13
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; } public void clear() {setAge(0); gpa = 0.0; } ILLEGALLEGAL private methods of a base class are not accessible by the derived class.
14
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
15
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 ?
16
The Object class Method Summary protected Object Object cloneclone() Creates and returns a copy of this object. boolean equalsequals(Object obj) Indicates whether some other object is "equal to" this one.Object String toStringtoString() Returns a string representation of the object. Every class is a subclass of the java.lang.Object class, even if not specified directly. 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 Automatically Called on an object whenever it is placed inside System.out.print(…
17
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; } }
18
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
19
Exercise to try at home public class Course {public int courseNumber = 114; } public class Classroom { public String building = "Javits"; public int roomNumber = 100; public String toString() { return building + roomNumber; } } 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?
20
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
21
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) Person Instructor A class may have any number of ancestors, in this case Instructor has 2. EmployeeStudent
22
Inheritance Diagrams – family tree? Joe Bob Mary Joe Little Bob Cletus Old Man Up the Mountain Uncle Ernie Elvira Mama Fat Irma Selma Sue Mary Joe The Town Drunk Farmer’s daughter across state line Elvis Danger: The family tree is crossing!
23
Inheritance Diagram Example Object Component Container Window Frame JFrame JComponent JPanelAbstractButton JButton A class may only have 1 immediate parent No criss-crossing in a class tree
24
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() …
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.