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.

Slides:



Advertisements
Similar presentations
Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
Advertisements

Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 8 Inheritance and.
Chapter 13 - Inheritance and Polymorphism The Object Class The equals Method The toString Method Polymorphism Dynamic Binding Compilation Details Polymorphism.
Class Hierarchies. Inheritance is the capability of a class to use the properties and methods of another class while adding its own functionality. An.
Intro to OOP with Java, C. Thomas Wu Inheritance and Polymorphism
Java Inheritance. What is inherited A subclass inherits variables and methods from its superclass and all of its ancestors. The subclass can use these.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
 In inheritance the child (subclass) chooses its parent (superclass)  Remember - only public or “protected” methods and variables are inherited  Should.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Inheritance. In this chapter, we will cover: The concept of inheritance Extending classes Overriding superclass methods Working with superclasses that.
Java boot camp1 Subclasses Concepts: The subclass and inheritance: subclass B of class A inherits fields and methods from A. A is a superclass of B. Keyword.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
1 Introduction to Inheritance Overview l Inheritance ensures Reusability l Example of Inheritance l What is actually Inherited? l Overloading Vs. Overriding.
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
CS 61B Data Structures and Programming Methodology July David Sun.
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,
1 Abstract Class There are some situations in which it is useful to define base classes that are never instantiated. Such classes are called abstract classes.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
What is inheritance? It is the ability to create a new class from an existing class.
 2002 Prentice Hall. All rights reserved. 1 Introduction to Inheritance Inheritance: –1 of 3 main features of OOP –Form of software reusability –(Derived)
Inheritence Put classes into a hierarchy derive a new class based on an existing class with modifications or extensions. Avoiding duplication and redundancy.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
CSC 142 Computer Science II Zhen Jiang West Chester University
MIT AITI 2003 – Lecture 12 Inheritance. What is Inheritance?  Real World Example: We inherit traits from our mother and father. We also inherit traits.
Inheritance CSC 171 FALL 2004 LECTURE 18. READING Read Horstmann, Chapter 11.
Inheritance in the Java programming language J. W. Rider.
Parameters… Classes Cont Mrs. C. Furman October 13, 2008.
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.,
1 Chapter 5 - Object-Oriented Programming 1 What is inheritance? Object-oriented systems allow classes to be defined in terms of other classes. Classes.
Inheritance (Part 2) Notes Chapter KomondorBloodHound PureBreedMix Dog Object Dog extends Object PureBreed extends Dog Komondor extends PureBreed.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Inheritance and Design CSIS 3701: Advanced Object Oriented Programming.
MIT AITI 2004 – Lecture 13 Abstract Classes and Interfaces.
Object Oriented Programming
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
1.00 Lecture 12 Inheritance. Inheritance allows you to write new classes based on existing (super) classes – Inherit super class methods and data – Add.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
CS100A, 15 Sept Lecture 5 1 CS100A, 5 Sept This lecture continues the discussion of classes. The important new concept of this lecture is.
CMSC 202 Polymorphism. 10/20102 Topics Binding (early and late) Upcasting and downcasting Extensibility The final modifier with  methods  classes.
CS100A, Fall Lecture 5 1 CS100A, Fall 1997 Lecture, Tuesday, 16 September. This lecture continues the discussion of classes. The important new concept.
Inheritance ndex.html ndex.htmland “Java.
Java Inheritance in Java. Inheritance Inheritance is a mechanism in which one object acquires all the properties and behaviors of parent object. The idea.
Java Inheritance 1/13/2015. Learning Objectives Understand how inheritance promotes software reusability Understand notions of superclasses and subclasses.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
CMSC 202 Polymorphism 2 nd Lecture. Aug 6, Topics Constructors and polymorphism The clone method Abstract methods Abstract classes.
BY:- TOPS Technologies
CS 112 Introduction to Programming Class Inheritance Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone:
Lecture 12 Inheritance.
Java Inheritance.
Week 8 Lecture -3 Inheritance and Polymorphism
CSC 113 Tutorial QUIZ I.
More inheritance, Abstract Classes and Interfaces
Polymorphism and access control
CMSC 202 Polymorphism.
Inheritance.
CS18000: Problem Solving and Object-Oriented Programming
Java Inheritance.
Inheritance.
Chapter 11 Inheritance and Polymorphism Part 1
Chapter 11 Inheritance and Encapsulation and Polymorphism
Topics OOP Review Inheritance Review Abstract Classes
មជ្ឈមណ្ឌលកូរ៉េ សហ្វវែរ អេច អ ឌី
Presentation transcript:

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 from our grandmother, grandfather, and ancestors. We might have similar eyes, the same smile, a different height... but we are in many ways "derived" from our parents.  In software: Object inheritance is more well defined! Objects that are derived from other object "resemble" their parents by inheriting both state (fields) and behavior (methods).

Dog Class public class Dog { private String name; private int fleas; public Dog(String n, int f) { name = n; fleas = f; } public String getName() { return name; } public int getFleas() { return fleas; } public void speak() { System.out.println("Woof"); }

Cat Class public class Cat { private String name; private int hairballs; public Cat(String n, int h) { name = n; hairballs = h; } public String getName() { return name; } public int getHairballs() { return hairballs; } public void speak() { System.out.println("Meow"); }

Problem: Code Duplication Dog and Cat have the name field and the getName method in common Classes often have a lot of state and behavior in common Result: lots of duplicate code!

Solution: Inheritance Inheritance allows you to write new classes that inherit from existing classes The existing class whose properties are inherited is called the "parent" or superclass The new class that inherits from the super class is called the "child" or subclass Result: Lots of code reuse!

Dog String name int fleas String getName() int getFleas() void speak() Cat String name int hairballs String getName() int getHairballs() void speak() Dog int fleas int getFleas() void speak() Cat int hairballs int getHairballs() void speak() Animal String name String getName() using inheritance superclass subclass

Animal Superclass public class Animal { private String name; public Animal(String n) { name = n; } public String getName() { return name; }

Dog Subclass public class Dog extends Animal { private int fleas; public Dog(String n, int f) { super(n); // calls Animal constructor fleas = f; } public int getFleas() { return fleas; } public void speak() { return System.out.println("Woof"); }

Cat Subclass public class Cat extends Animal { private int hairballs; public Cat(String n, int h) { super(n); // calls Animal constructor hairballs = h; } public int getHairballs() { return hairballs; } public void speak() { return System.out.println("Meow"); }

Inheritance Quiz 1 What is the output of the following? Dog d = new Dog("Rover" 3); Cat c = new Cat("Kitty", 2); System.out.println(d.getName() + " has " + d.getFleas() + " fleas"); System.out.println(c.getName() + " has " + c.getHairballs() + " hairballs"); Rover has 3 fleas Kitty has 2 hairballs (Dog and Cat inherit the getName method from Animal)

Inheritance Rules Use the extends keyword to indicate that one class inherits from another The subclass inherits all the fields and methods of the superclass Use the super keyword in the subclass constructor to call the superclass constructor

Subclass Constructor The first thing a subclass constructor must do is call the superclass constructor This ensures that the superclass part of the object is constructed before the subclass part If you do not call the superclass constructor with the super keyword, and the superclass has a constructor with no arguments, then that superclass constructor will be called implicitly.

Implicit Super Constructor Call If I have this Food class: public class Food { private boolean raw; public Food() { raw = true; } then this Beef subclass: public class Beef extends Food { private double weight; public Beef(double w) { weight = w } } is equivalent to: public class Beef extends Food { private double weight; public Beef(double w) { super(); weight = w } }

Inheritance Quiz 2 public class A { public A() { System.out.println("I'm A"); } } public class B extends A { public B() { System.out.println("I'm B"); } } public class C extends B { public C() { System.out.println("I'm C"); } } What does this print out? C x = new C(); I'm A I'm B I'm C

Subclasses can override methods in their superclass What is the output of the following? ThermUS thermometer = new ThermUS(100); System.out.println(thermometer.getTemp()); Overriding Methods class ThermUS extends Therm { public ThermUS(double c) { super(c); } // degrees in Fahrenheit public double getTemp() { return celsius * ; } class Therm { public double celsius; public Therm(double c) { celsius = c; } public double getTemp() { return celcius; } 212

Calling Superclass Methods When you override a method, you can call the superclass's copy of the method by using the syntax super.method() class Therm { private double celsius; public Therm(double c) { celcius = c; } public double getTemp() { return celcius; } class ThermUS extends Therm { public ThermUS(double c) { super(c); } public double getTemp() { return super.getTemp() * ; }

Access Level Classes can contain fields and methods of four different access levels: private: access only to the class itself package: access only to classes in the same package protected: access to classes in the same package and to all subclasses public: access to all classes everywhere

Variable Type vs Object Type Variables have the types they are given when they are declared and objects have the type of their class. For an object to be assigned to a variable is must be of the same class or a subclass of the type of the variable. You may not call a method on a variable if it's type does not have that method, even if the object it references has the method.

Which Lines Don't Compile? public static void main(String[] args) { Animal a1 = new Animal(); a1.getName(); a1.getFleas(); a1.getHairballs(); a1.speak(); Animal a2 = new Dog(); a2.getName(); a2.getFleas(); a2.getHairballs(); a2.speak(); Dog d = new Dog(); d.getName(); d.getFleas(); d.getHairballs(); d.speak(); } // Animal does not have getFleas // Animal does not have getHairballs // Animal does not have speak // Animal does not have getFleas // Animal does not have getHairballs // Animal does not have speak // Dog does not have getHairballs

Remember Casting? "Casting" means "promising" the compiler that the object will be of a particular type You can cast a variable to the type of the object that it references to use that object's methods without the compiler complaining. The cast will fail if the variable doesn't reference an object of that type.

Which Castings Will Fail? public static void main(String[] args) { Animal a1 = new Animal(); ((Dog)a1).getFleas(); ((Cat)a1).getHairballs(); ((Dog)a1).speak(); Animal a2 = new Dog(); ((Dog)a2).getFleas(); ((Cat)a2).getHairballs(); ((Dog)a2).speak(); Dog d = new Dog(); ((Cat)d).getHairballs(); } // a1 is not a Dog // a1 is not a Cat // a1 is not a Dog // a2 is not a Cat // d is not a Cat

Programming Example A Company has a list of Employees. It asks you to provide a payroll sheet for all employees. –Has extensive data (name, department, pay amount, …) for all employees. –Different types of employees – manager, engineer, software engineer. –You have an old Employee class but need to add very different data and methods for managers and engineers. Suppose someone wrote a name system, and already provided a legacy Employee class. The old Employee class had a printData() method for each Employee that only printed the name. We want to reuse it, and print pay info. Borrowed with permission from Course 1.00 Notes

public … Main(…){ Employee e1…("Mary","Wang");... e1.printData(); // Prints Employee names.... } Employee e1 lastName firstName printData Encapsulation Message passing"Main event loop" private: REVIEW PICTURE

Employee class class Employee { // Data private String firstName, lastName; // Constructor public Employee(String fName, String lName) { firstName= fName; lastName= lName; } // Method public void printData() { System.out.println(firstName + " " + lastName);} } This is a simple super or base class.

Inheritance Class Employee firstName lastName printData() Class Manager salary firstName lastName Class Engineer hoursWorked wages firstName lastName printData() getPay() is-a printData() getPay() Already written: is-a You next write:

Engineer class class Engineer extends Employee { private double wage; private double hoursWorked; public Engineer(String fName, String lName, double rate, double hours) { super(fName, lName); wage = rate; hoursWorked = hours; } public double getPay() { return wage * hoursWorked; } public void printData() { super.printData(); // PRINT NAME System.out.println("Weekly pay: $" + getPay(); } } Subclass or (directly) derived class

Manager class class Manager extends Employee { private double salary; public Manager(String fName, String lName, double sal){ super(fName, lName); salary = sal; } public double getPay() { return salary; } public void printData() { super.printData(); System.out.println("Monthly salary: $" + salary);} } Subclass or (directly) derived class

Inheritance… Class Manager Salary firstName lastName printData getPay Class SalesManager firstName lastName printData getPay Salary salesBonus is-a

SalesManager Class class SalesManager extends Manager { private double bonus; // Bonus Possible as commission. // A SalesManager gets a constant salary of $ public SalesManager(String fName, String lName, double b) { super(fName, lName, ); bonus = b; } public double getPay() { return ; } public void printData() { super.printData(); System.out.println("Bonus Pay: $" + bonus; } } (Derived class from derived class)

Main method public class PayRoll { public static void main(String[] args) { // Could get Data from tables in a Database. Engineer fred = new Engineer("Fred", "Smith", 12.0, 8.0); Manager ann = new Manager("Ann", "Brown", ); SalesManager mary= new SalesManager("Mary", "Kate", ); // Polymorphism, or late binding Employee[] employees = new Employee[3]; employees[0]= fred; employees[1]= ann; employees[2]= mary; for (int i=0; i < 3; i++) employees[i].printData(); } Java knows the object type and chooses the appropriate method at run time

Output from main method Fred Smith Weekly pay: $96.0 Ann Brown Monthly salary: $ Mary Barrett Monthly salary: $ Bonus: $ Note that we could not write: employees[i].getPay(); because getPay() is not a method of the superclass Employee. In contrast, printData() is a method of Employee, so Java can find the appropriate version.

Object Class All Java classes implicitly inherit from java.lang.Object So every class you write will automatically have methods in Object such as equals, hashCode, and toString. We'll learn about the importance of some of these methods in later lectures.