1 / 24

CSE 114 – Computer Science I Inheritance

CSE 114 – Computer Science I Inheritance. Yosemite National Park, California. 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

cybele
Download Presentation

CSE 114 – Computer Science I Inheritance

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CSE 114 – Computer Science IInheritance 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. Means Student inherits all instance variables and methods from Person Runs Person’s constructor 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 < 0.0 || newGpa > 4.0) gpa = 0.0; else gpa = newGpa; } }

  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 < 0 || 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! NO! YES! YES! NO! YES! NO! YES!

  13. ILLEGAL LEGAL 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; } • private methods of a base class are not accessible by the derived class.

  14. Runs the previously defined Student constructor 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; }

  15. What happens if you forget super? 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; }

  16. Method Summary String toString()           Returns a string representation of the object. protected  Object clone()          Creates and returns a copy of this object. boolean equals(Object obj)           Indicates whether some other object is "equal to" this one. Automatically Called on an object whenever it is placed inside System.out.print(… The Object class • Every class is a subclass of the java.lang.Objectclass, 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

  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. Student Employee Instructor 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 • A class may have any number of ancestors, in this case Instructor has 2.

  22. Danger: The family tree is crossing! 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

  23. Inheritance Diagram Example • A class may only have 1 immediate parent • No criss-crossing in a class tree Object Component Container JComponent Window Frame JPanel AbstractButton JFrame JButton

  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() …

More Related