Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types.

Slides:



Advertisements
Similar presentations
1 Inheritance Chapter 9. 2 Module Outcomes To develop a subclass from a superclass through inheritance To invoke the superclass ’ s constructors and methods.
Advertisements

09 Inheritance. 2 Contents Defining Inheritance Relationships of Inheritance Rules of Inheritance super and this references super() and this() methods.
23-May-15 Polymorphism. 2 Signatures In any programming language, a signature is what distinguishes one function or method from another In C, every function.
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.
15-Jun-15 Polymorphism. 2 Signatures In any programming language, a signature is what distinguishes one function or method from another In C, every function.
CSCI 143 OOP – Inheritance 1. What is Inheritance? A form of software reuse Create a new class from an existing class – Absorb existing class data and.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
26-Jun-15 Polymorphism. 2 Legal assignments Widening is legal Narrowing is illegal (unless you cast) class Test { public static void main(String args[])
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
Inheritance and interfaces A class C1 is derived from class C2, then C1 is called subclass, and C2 is called superclass Superclass-parent, base class Subclass.
Unit 011 Inheritance Recall What Inheritance is About The extends Keyword The Object Class Overriding versus Overloading What is Actually Inherited? Single.
Abstract Classes and Interfaces
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
Chapter 11 Abstract Classes and Interfaces 1. Abstract method New modifier for class and method: abstract An abstract method has no body Compare: abstract.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
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,
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Intro to OOP with Java, C. Thomas Wu
What is inheritance? It is the ability to create a new class from an existing class.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
CSC 142 Computer Science II Zhen Jiang West Chester University
Some Object-Oriented Programming (OOP) Review. Let’s practice writing some classes Write an Employee class with methods that return values for the following.
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.,
Peyman Dodangeh Sharif University of Technology Fall 2014.
Topic 4 Inheritance.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Inheritance and Access Control CS 162 (Summer 2009)
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Chapter 8 Inheritance. 2  Review of class relationships  Uses – One class uses the services of another class, either by making objects of that class.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Object Inheritance Lecturer: Kalamullah Ramli Electrical Engineering Dept. University of Indonesia Session-4.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved COS240 O-O Languages AUBG,
More on Objects Mehdi Einali Advanced Programming in Java 1.
Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.
Peyman Dodangeh Sharif University of Technology Fall 2014.
1 / 71 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 4 Programming Fundamentals using Java 1.
1 Interfaces and Abstract Classes The ability to define the behavior of an object without specifying that behavior is to be implemented Interface class.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Inheritance ndex.html ndex.htmland “Java.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
Object-Oriented Programming: Polymorphism Chapter 10.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and Polymorphism.
28-Dec-04polymorhism.ppt1 Polymorphism. 28-Dec-04polymorhism.ppt2 signatures in any programming language, a signature is what distinguishes one function.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Object Oriented Programming. Constructors  Constructors are like special methods that are called implicitly as soon as an object is instantiated (i.e.
Advanced Programming in Java
Object-oriented Programming in Java
Chapter 11 Inheritance and Polymorphism
Advanced Programming in Java
Chapter 5 Hierarchies IS-A associations superclasses subclasses
ATS Application Programming: Java Programming
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Polymorphism 11-Nov-18.
Polymorphism 15-Nov-18.
More inheritance, Abstract Classes and Interfaces
Constructors under inheritance Variable Shadowing
Java Programming Language
Polymorphism 21-Apr-19.
Chapter 11 Inheritance and Polymorphism Part 1
Presentation transcript:

Inheritance

Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types of personnel. Much of the code for different classifications of personnel would be identical This was often handled by cutting and pasting code and then modifying Needed a way to capture and formalize the similarity

Inheritance Natural, hierarchical way of organizing things. Staff Member Employee Volunteer Hourly Salaried Consultant Think in terms of “is a” relationships: An Employee is a Staff Member, as is a Volunteer. An Hourly worker is a(n) Employee. A Consultant is a(n) Hourly employee. (subclass of Hourly) (subclass of Employee) (subclass of Staff) (superclass)

Classes and Subclasses class Animal { public String name = ""; public String noise = ""; public int numTimesPerformed = 0; // constructors, accessors & modifiers go here public void identifySelf( ) { System.out.println(“My name is “ + name); } // of identifySelf public void perform( ) { doYourThing( ); numTimesPerformed++; } // of perform public void doYourThing( ) { ; // ‘no-op’ method } // of doYourThing } // of Animal Don’t worry about “private” and “public” for now So, animals have a name and noise and they can identify themselves, perform and do their thing. Animal harpo = new Animal(); harpo.setName(“Harpo”); harpo.doYourThing(); // says nothing

Subclasses (Dog extends Animal i.e. “A dog is an animal” or “All dogs are animals”) class Dog extends Animal { public Dog() { noise = “Woof”; } // of constructor public void doYourThing ( ) { identifySelf(); System.out.println(“I am a dog”); System.out.println(noise); } // of doYourThing } // of Dog Recall: The Animal class had a no-op method for doYourThing() Dog pickles = new Dog(); pickles.setName(“Pickles”); pickles.doYourThing(); // output: // “My name is Pickles” // “I am a dog” // “Woof” Animal Dog Cat Human

Subclasses (Cat extends Animal i.e. “A cat is an animal” or “All cats are animals”) class Cat extends Animal { public Cat() { noise = “Miaow”; } // of constructor public void doYourThing ( ) { identifySelf(); System.out.println(“I am a cat”); System.out.println(noise); } // of doYourThing } // of Cat Cat abby = new Cat(); abby.setName(“Abby”); abby.doYourThing(); // output: // “My name is Abby” // “I am a cat” // “Miaow” Animal Dog Cat Human

Subclasses (Human extends Animal i.e. “A human is an animal” or “All humans are animals”) class Human extends Animal { public Human() { noise = “I think therefore I am”; } // of constructor public void doYourThing ( ) { identifySelf(); System.out.println(“I am a sentient being”); System.out.println(noise); } // of doYourThing } // of Human Human descartes = new Human(); descartes.setName(“Rene”); descartes.doYourThing(); // output: // “My name is Rene” // “I am a sentient being” // “I think therefore I am” Animal Dog Cat Human

Questions?

Inheritance & Scope Using super & this

Inheritance and Scope Variables (e.g. noise): Java first examines current method, looks for local variable or parameter; Java then examines current class (e.g. Dog); Java then examines superclass (e.g. Animal); Java continues up the class hierarchy until no more superclasses to examine. Methods (e.g. doYourThing() or identifySelf()): Java first examines current class; Java then examines superclass; Java continues up inheritance hierarchy until no more superclasses to examine.

Specifying Scope Java allows you to override the scope rules by saying which variable/method you’re referring to: Keyword super: keyword for specifying method or variable from superclass, e.g., super.doYourThing( ) Keyword this: keyword for specifying method or variable in current object, e.g., this.doYourThing( )

Using super & this class Dog extends Animal { public Dog() { super.noise = “Woof”; } // of constructor public void doYourThing ( ) { super.identifySelf(); System.out.println(“I am a dog”); System.out.println(noise); } // of doYourThing } // of Dog Same (in this case) as noise = “Woof”; and this.noise = “Woof”; Animal Dog Cat Human Same (in this case) as identifySelf(); or this.identifySelf(); (but why??)

Using super and this class Animal { String name; } class Dog extends Animal { String name; /* Just so I don't forget! */ void twoNames() { System.out.println ("My dog name is " + name); System.out.println ("My animal name is " + super.name); }

Using super class Dog extends Animal { // constructor as before public void doYourThing() { identifySelf(); System.out.println(noise); } // of doYourThing public void identifySelf() { super.identifySelf(); System.out.println(“I am a dog”); } // of identifySelf } // of Dog Animal Dog Cat Human I.e. this.identifySelf() (newly defined below) I.e. the identifySelf() (defined in Animal) If omitted???

class Shape { public String name; public String getName () { return (this.name); } // getName public int area () { return (0); } // area } // Shape A geometry example Shape CircleRectangle Each extending object would override the area() method.

class Rectangle extends Shape { private int length, width; Rectangle () { this(0, 0); } // constructor Rectangle (int l, int w) { this( l, w, “rectangle”); } // constructor Rectangle (int l, int w, String n) { length = l; width = l; name = n; } // constructor public int area () { return (length * width); } // area public String getName () { if (length == width) return "square"; else return super.getName()); } // getName public String toString () { String s; s = new String ("A " + getName() + " with length " + length + " and width " + width); return (s); } } // toString } // Rectangle Constructor “chaining” The Circle class implementation is left as an exercise to the reader.

Java’s rule: If first line of constructor is not an explicit call to a superclass constructor, Java will implicitly put super( ) as the first line, calling the superclass default constructor. public Dog() { strNoise = “Woof”; } // of constructor An exception to this rule: chained constructor call to this(params) will defer(ertelemek) super( ) call To use superclass constructors with params, call them explicitly, e.g., super(strName) Constructors and Inheritance implied call to Animal() here

Look Closer... class Rectangle extends Shape { private int length, width; Rectangle () { this(0, 0); } // constructor Rectangle (int l, int w) { this( l, w, “rectangle”); } // constructor Rectangle (int l, int w, String n) { length = l; width = l; name = n; } // constructor public int area () { return (length * width); } // area Shape(); What if there is no Shape()??? What if I want a Shape constructor run here? Error

Inheritance and Scoping Examples: super(xxx) // calls a superclass constructor super.xxx // accesses superclass’ variable super.xxx( ) // calls superclass’ method this(xxx) // calls a current-class constructor this.xxx // accesses current class’s variable this.xxx( ) // calls current class’ method Note: cannot do super.super (can achieve this effect via casting, but rarely should; details later...)

Chaining, superclass example

class Parent { String name; public Parent() { setName("NONE"); cp(1); } public Parent(String name) { setName(name); cp(2); } public void setName(String name) { this.name = name; cp(3); } public void cp(int n) { System.out.println("At checkpoint "+n+" "+name); } public static void main(String args[]) { Child c = new Child(); } } // Parent class Child extends Parent { public Child() { this("NONAME"); cp(4); } public Child(String name) { this.name = name; cp(5); } } // Child Output: At checkpoint 3 NONE At checkpoint 1 NONE At checkpoint 5 NONAME At checkpoint 4 NONAME

class Parent { String name; public Parent() { setName("NONE"); cp(1); } public Parent(String name) { setName(name); cp(2); } public void setName(String name) { this.name = name; cp(3); } public void cp(int n) { System.out.println("At checkpoint "+n+" "+name); } public static void main(String args[]) { Child c = new Child("Bob"); } } // Parent class Child extends Parent { public Child() { this("NONAME"); cp(4); } public Child(String name) { this.name = name; cp(5); } } // Child Output: At checkpoint 3 NONE At checkpoint 1 NONE At checkpoint 5 Bob

Recall: Class Object Java provides a base class, Object All classes that do not have an extends clause implicitly inherit directly from class java.lang.Object Examples utilizing this fact: public boolean equals (Object o); public boolean String toString (); overriding When you create your own toString( ) method for a class, you are overriding the toString( ) provided by Object.

Object Hierarchy Animal Dog Cat Human Object Employee Salaried Hourly class Object methods: String toString() boolean equals(Object obj) and a few others... Animal Dog Cat Human Object Employee Salaried Hourly Or how about...

Questions?

Primitive types (e.g., int) are not classes But sometimes, we may have need to make use of primitive types in a context that requires that we manipulate objects, not primitives e.g. many collection classes are collections of Objects Java provides a set of wrapper classes (a.k.a. type wrappers, a.k.a. envelope classes) to support treating primitives as objects. It does this by providing a specific class that corresponds to each primitive data type They are in java.lang, so the names are universally available The names are mostly identical to primitive types, but capitalized... Wrapper Classes

Class corresponds to Primitive Boolean boolean Character char Byte byte Short short Integer int Long long Float float Double double Each one: allows us to manipulate primitives as objects contains useful conversion methods. E.g. Integer contains static Integer valueOf(String s) Integer.valueOf("27") is the object corresponding to int 27 contains useful utility methods (e.g. for hashing)

Using wrappers to bridge between objects and primitives: // create and initialize an int int i = 7; // create an Integer object and convert the int to it Integer intObject = new Integer( i ); // retrieve the int by unwrapping it from the object System.out.println( intObject.intValue() ); // convert a string into an Integer object String strS = "27"; Integer intObject intObject = new Integer (strS); // then to an int int a = intObject.intValue(); // one way int b = Integer.parseInt(strS); // second way Wrapper Classes

Questions?