24
CSE 114 – Computer Science I Inheritance Yosemite National Park, California

CSE 114 – Computer Science I Inheritance

  • Upload
    cybele

  • View
    49

  • Download
    1

Embed Size (px)

DESCRIPTION

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 - PowerPoint PPT Presentation

Citation preview

CSE 114 – Computer Science IInheritance

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– 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

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

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: Personpublic 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: Studentpublic 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; }

}

Runs Person’s constructor

Means Student inherits all instance

variables and methods from Person

Example: Child (Sub-)Class: Employeepublic 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 classespublic 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!YES!

NO!

NO!

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;

}

public void clear()

{ setAge(0);

gpa = 0.0;

}

ILLEGAL 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?

The Object class

Method Summary

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.

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

Overriding toString() method Examplepublic 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.0Curly Stooge, age 0, Salary: $0

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?

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)

Person

Instructor

• A class may have any number of ancestors, in this case Instructor has 2.

EmployeeStudent

Inheritance Diagrams – family tree?

JoeBob

MaryJoe

LittleBob

Cletus

Old Man Up the

Mountain

UncleErnie

Elvira

Mama

FatIrma

SelmaSue

MaryJoe

The TownDrunk

Farmer’s daughter across

state line

Elvis

Danger: The family tree is

crossing!

Inheritance Diagram Example

Object

Component

Container

Window

Frame

JFrame

JComponent

JPanel AbstractButton

JButton

• A class may only have 1 immediate parent

• No criss-crossing in a class tree

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