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

Slides:



Advertisements
Similar presentations
Written by: Dr. JJ Shepherd
Advertisements

1 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
CMSC 202 Inheritance. Aug 6, Object Relationships An object can have another object as one of instance variables. The Person class had two Date.
Inheritance Inheritance Reserved word protected Reserved word super
OBJECT-ORIENTED PROGRAMMING. What is an “object”? Abstract entity that contains data and actions Attributes (characteristics) and methods (functions)
1. 2 Introduction to Inheritance  Access Modifiers  Methods in Subclasses  Method Overriding  Converting Class Types  Why up-cast?  Why down-cast?
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
Inheritance. 2 Inheritance allows a software developer to derive a new class from an existing one The existing class is called the parent class or superclass.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
1 Inheritance Overview l Inheritance ensures Reusability l Example of Inheritance l What is actually Inherited? l Overloading Vs. Overriding l Object:
1 Chapter 7 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
1 Lecture 4 Further OO Concepts I - Polymorphism Overview  What is polymorphism?  Why polymorphism is wonderful?  Why is Upcasting useful?  What is.
Unit 031 Interfaces What is an Interface? Interface Declaration Syntax Implementing Interfaces Using Interfaces as Types Interfaces and Inheritance Interfaces.
Inheritance and Polymorphism Recitation – 10/(16,17)/2008 CS 180 Department of Computer Science, Purdue University.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
Unit 031 Interfaces What is an Interface? Interface Declaration Syntax Implementing Interfaces Using Interfaces as Types Interfaces and Inheritance Interfaces.
Unit 011 Inheritance Recall What Inheritance is About The extends Keyword The Object Class Overriding versus Overloading What is Actually Inherited? Single.
1 Introduction to Inheritance Overview l Inheritance ensures Reusability l Example of Inheritance l What is actually Inherited? l Overloading Vs. Overriding.
Chapter 11: Inheritance and Polymorphism Java Programming: Program Design Including Data Structures Program Design Including Data Structures.
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,
Chapter 8 More Object Concepts
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
CSC 142 Computer Science II Zhen Jiang West Chester University
Programming using C# for Teachers Introduction to Objects Reference Types Functions of Classes Attributes and Types to a class LECTURE 2.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
JAVA Classes Review. Definitions Class – a description of the attributes and behavior of a set of computational objects Constructor – a method that is.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
1 final (the keyword, not the exam). 2 Motivation Suppose we’ve defined an Employee class, and we don’t want someone to come along and muck it up  E.g.,
MIT AITI 2004 – Lecture 12 Inheritance. What is Inheritance?  In the real world: We inherit traits from our mother and father. We also inherit traits.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
MIT AITI 2004 – Lecture 13 Abstract Classes and Interfaces.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved COS240 O-O Languages AUBG,
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
CS 116 Lecture 1 John Korah Contains content provided by George Koutsogiannakis & Matt Bauer.
1 C# - Inheritance and Polymorphism. 2 1.Inheritance 2.Implementing Inheritance in C# 3.Constructor calls in Inheritance 4.Protected Access Modifier 5.The.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Inheritance and Polymorphism
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
OOP Basics Classes & Methods (c) IDMS/SQL News
COMP Inheritance and Polymorphism Yi Hong June 09, 2015.
COMPUTER SCIENCE & TECHNOLOGY DEGREE PROGRAMME FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UVA WELLASSA ‏ Properties of Object Oriented Programming.
BY:- TOPS Technologies
Programming in Java Transitioning from Alice. Becomes not myFirstMethod but …. public static void main (String[] arg) { // code for testing classes goes.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Lecture 12 Inheritance.
Chapter 11 Inheritance and Polymorphism
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
CS 302 Week 11 Jim Williams, PhD.
User-Defined Classes and ADTs
Chapter 9 Inheritance and Polymorphism
Inheritance Inheritance is a fundamental Object Oriented concept
Defining Classes and Methods
Java Inheritance.
Object-Oriented Programming
Chapter 11 Inheritance and Polymorphism Part 1
CIS 110: Introduction to computer programming
Presentation transcript:

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 –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: 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; } 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

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 ) 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);// 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!

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.

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

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

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

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

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