1 Inheritance in Java CS 3331 Fall 2009. 2 Outline  Overloading  Inheritance and object initialization  Subtyping  Overriding  Hiding.

Slides:



Advertisements
Similar presentations
A subclass can add new private instance variables A subclass can add new public, private or static methods A subclass can override inherited methods A.
Advertisements

METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 8 Inheritance and.
OOP: Inheritance By: Lamiaa Said.
1 Inheritance Chapter 9. 2 Module Outcomes To develop a subclass from a superclass through inheritance To invoke the superclass ’ s constructors and methods.
09 Inheritance. 2 Contents Defining Inheritance Relationships of Inheritance Rules of Inheritance super and this references super() and this() methods.
Object-Oriented Programming CS 3360 Spring 2012 Sec , Adapted from Addison Wesley’s lecture notes (Copyright © 2004 Pearson Addison.
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.
1 Lecture 3 Inheritance. 2 A class that is inherited is called superclass The class that inherits is called subclass A subclass is a specialized version.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Inheritance and Polymorphism Recitation – 10/(16,17)/2008 CS 180 Department of Computer Science, Purdue University.
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.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Unit 011 Inheritance Recall What Inheritance is About The extends Keyword The Object Class Overriding versus Overloading What is Actually Inherited? Single.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
OOPs Object oriented programming. Based on ADT principles  Representation of type and operations in a single unit  Available for other units to create.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved COS240 O-O Languages AUBG,
Intro to OOP with Java, C. Thomas Wu
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Java Implementation: Part 3 Software Construction Lecture 8.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
Inheritance. Introduction Inheritance is one of the cornerstones of object-oriented programming because it allows the creation of hierarchical classifications.
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.
C# F 1 CSC 298 Object Oriented Programming (Part 1)
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
Inheritance and Access Control CS 162 (Summer 2009)
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.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
OOPs Object oriented programming. Abstract data types  Representationof type and operations in a single unit  Available for other units to create variables.
1 The finalize, clone, and getClass Methods  The finalize method is invoked by the garbage collector on an object when the object becomes garbage.  The.
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.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Lecture 4: Extending Classes. Concept Inheritance: you can create new classes that are built on existing classes. Through the way of inheritance, you.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
1 Chapter 4 Inheritance and Polymorphism. 2 Objectives u To develop a subclass from a superclass through inheritance. u To invoke the superclass’s constructors.
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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
CS 112 Programming 2 Lecture 06 Inheritance & Polymorphism (1)
1 Chapter 2 Inheritance and Polymorphism. 2 Objectives u To develop a subclass from a superclass through inheritance. u To invoke the superclass’s constructors.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and Polymorphism.
CS 3180 (Prasad)L67Classes1 Classes and Interfaces Inheritance Polymorphism.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
CS102 Algorithims and Programming II1 Inheritance Inheritance defines a relationship among classes. A class C2 may inherit from (extend – derive from)
Modern Programming Tools And Techniques-I
Chapter 11 Inheritance and Polymorphism
Chapter 11 Inheritance and Polymorphism
Inheritance and Polymorphism
COP 3331 Object Oriented Analysis and Design Chapter 5 – Classes and Inheritance Jean Muhammad.
Continuing Chapter 11 Inheritance and Polymorphism
CSC 143 Inheritance.
Overloading and Constructors
Chapter 9 Inheritance and Polymorphism
Extending Classes.
Chapter 9 Inheritance and Polymorphism
Inheritance in Java CS 3331 Fall 2009.
Chapter 11 Inheritance and Polymorphism Part 2
Chapter 11 Inheritance and Encapsulation and Polymorphism
Overloading Each method has a signature: its name together with the number and types of its parameters Methods Signatures String toString()
Presentation transcript:

1 Inheritance in Java CS 3331 Fall 2009

2 Outline  Overloading  Inheritance and object initialization  Subtyping  Overriding  Hiding

3 Overloading of Methods and Constructors  Def. Overloading The ability to allow different methods or constructors of a class to share the same name. public class Point { public Point() { /* … */ } public Point(int x, int y) { /* … */ } public double distance(Point other) { /* … */ } public double distance(int x, int y) { /* … */ } public double distance() { /* … */ } // … } constructor overloading method overloading

4 Overloading (Cont.)  Which overloaded method to invoke? Resolved at compile-time with signature matching, where signature is name and parameter types. Constructors/MethodsSignatures 1: Point() Point() 2: Point(int x,int y) Point(int,int) 3: double distance(Point other) distance(Point) 4: double distance(int x,int y)distance(int,int) 5: double distance()distance() Point p1 = new Point(); // which constructor? Point p2 = new Point(10,20); p2.distance(p1); // which method? p2.distance(20,30); p2.distance();

5 When to Overload? When there is a general, nondiscriminative description of the functionality that fits all the overloaded methods. public class StringBuffer { public StringBuffer append(String str) { /* … */ } public StringBuffer append(boolean b) { /* … */ } public StringBuffer append(char c) { /* … */ } public StringBuffer append(int i) { /* … */ } public StringBuffer append(long l) { /* … */ } // … }

6 When to Overload? (Cont.) When all the overloaded methods offer the same functionality, with some of them providing default arguments. public class String { public String substring(int i, int j) { // base method: return substring from index i to j - 1. } public String substring(int i) { // provide default argument return substring(i, length()); } // … }

7 Outline Overloading  Inheritance and object initialization  Subtyping  Overriding  Hiding

8 Inheritance  Inheritance models the is-a relationship.  If class S extends class T, then all objects of S can act-like an object of T.  Only single inheritance is allowed among classes.  All public and protected members of a superclass are accessible in the subclasses.* *All protected members are also accessible within the package.

9 Constructors of Subclasses  Can invoke a constructor of the direct superclass. super(…) must be the first statement. If the super constructor call is missing, by default the no-arg super() is invoked implicitly.  Can also invoke another constructor of the same class. this(…) must be the first statement.

10 Example of “this” Calls public class Point { private int x, y; public Point(int x, int y) { this.x = x; this.y = y; } public Point() { // default constructor this.x = 0; this.y = 0; } } this(0,0);

11 Example of “super” Calls public class ColoredPoint extends Point { private Color color; public ColoredPoint(int x, int y, Color color) { this.x = x; this.y = y; this.color = color; } public ColoredPoint(int x, int y) { this(x, y, Color.BLACK); // point with default value } public ColoredPoint() { color = Color.BLACK; // what will be the values of x and y? } } super(x,y); Point -x: int -y: int +Point() +Point(x: int, y: int)

12 Default Constructor public ClassName() { super(); } Q. What would be the use of default constructor?  If no constructor is defined, the following form of no-arg default constructor is automatically generated by the compiler.

13 Execution Order of Constructors public class T { int x = 10; // 1: first public T() { x = 20; // 2: second } //... } Rule: Superclass first and field initialization first - Instance variable initializer vs. instance initializer (or initialization block) Example: S x = new S(); public class S extends T { int y = 30; // 3: third public S() { super(); y = 40; // 4: fourth } //... }

14 Exercise class Super { protected int x = 100; } class Sub extends Super { { x = 200; } public static void main(String[] args) { System.out.println(new Sub().x); }  What value will be printed and why?

15 Exercise class ClassRoom extends Room { private int capacity = 60; public ClassRoom(int c) { capacity = c; } public ClassRoom(int n, int c) { super(n); } { if (number % 2 == 1) capacity *= 2; }  What are the room number and capacity of the following two objects, respectively? ClassRoom c1 = new ClassRom(100); ClassRoom c2 = new ClassRoom(300, 100); class Room { private int number = 100; public Room() { this(++nextNum); } public Room(int n) { number = n; } private static int nextNum = 100; static { nextNum += 100; } { number += 2; } }

16 Outline Overloading Inheritance  Subtyping  Overriding  Hiding

17 Types  What’re types? Sets of values  Why types? To statically detect program errors, called type errors. Typed- vs. untyped-languages (also, static vs. dynamic typing)  Types in Java Primitive types (e.g., boolean, int, long, etc.) Classes (e.g., Object, String, etc.) Interfaces (e.g., Runnable, List, etc.) Array types (e.g., int[], Object[], List[][], etc.)

18 Subtyping  What’s subtyping? Subset relationship among types (e.g., Manager is a subtype (or subset) of Employee) Subtype’s values are legitimate values of supertypes.  Why subtyping? Can organizes types into hierarchy, called subype hierarchy Can extend programs by adding subtypes  Subtyping in Java Between classes (subclassing) Between interfaces (subinterfacing) Between classes and interfaces (implementation or realization) Between arrays

19 Substitution Property  Def. Substitution property A value of subtype can appear where a value of its supertype is expected, e.g., in arguments, results, receivers, and assignments. // 1. argument // public void register(Student s); register(new PhDStudent(“Joe”)); // 2. return value public Student find(String name) { // I am lazy, so I am going to return Joe every time. return new PhDStudent(“Joe”); } // 3. receiver of method call // toString in the class Object new PhDStudent(“Joe”).toString();

20 Substitution Property (Cont.)  Rules of (polymorphic) assignment The type of expression at the right-hand side of an assignment must be a subtype of the type of the variable at the left-hand side of the assignment. class Student { … } class Undergraduate extends Student { … } class Graduate extends Student { … } Student s1, s2; s1 = new Undergradute(); // polymorphic assignment s2 = new Graudate(); // polymorphic assignment Graduate s3 = s2; // is this OK? Graduate s3 = (Graduate) s2; // explicit casting

21 Widening and Narrowing  Def. widening and narrowing The conversion of a subtype to one of its supertype is called widening, and the conversion of a supertype to one of its subtype is called narrowing (or downcasting). // s is a stack of strings Stack s = new Stack(); s.push(“Hello”); // widening: void push(Object) … // Stack defines a method top, i.e., “public Object top()”. s.top().size(); // okay? ((String) s.top()).size(); // downcasting

22 Outline Overloading Inheritance Subtyping  Overriding  Hiding

23 Overriding Methods  Def. Overriding Refers to the introduction of an instance method in a subclass that has the same name, signature, and return type of a method declared in the superclass.  Consequences Implementation of the method in the subclass replaces the implementation of the method in the superclass

24 Overriding Methods (Cont.) public class T { public void m() { … } } public class S extends T { public void m() { … } } T t = new T(); S s = new S(); t.m(); // invoke m of class T s.m(); // invoke m of class S

25 Overriding Methods (Cont.)  Dynamic dispatch (binding): The method to be invoked is determined at runtime by the runtime type of the object, not by the declared type (static type). class Student { public int minCredits() { return 12; } … } class GraduateStudent extends Student { public int minCredits() { return 9; } … } Student s; // … s.minCredits(); // which minCredits method?

26 Overriding Methods (Cont.)  Q. How overriding differ from overloading?

27 Implementation of Dynamic Binding  Storage structure of instance variables Class instance records (CIRs) store the state of an object The CIR for a subclass adds its new fields to the parent CIR.  Dynamic bindings of messages to methods Virtual Method Tables (VMTs) are used for dynamic binding.

28 Dynamic Binding (Cont.) class Point { private int x, y; public Point(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public int getY() { return y; } } class ColoredPoint extends Point { private Color color; public ColoredPoint(int x, int y, Color c) { super(x, y); color = c; } public Color getColor() { return color; } } xy…xy… x y color … CIR for ColoredPoint CIR for Point

29 super: vmt: … Point.class getX: getY: … class: x: 10 y: 20 color: p: Color.RED super: vmt: … ColoredPoint.class Dynamic Binding (Cont.) ColoredPoint p = new ColoredPoint(10,20,Color.RED); p.getColor(); p.getX(); Object.class super: vmt: … getColor: … Q: What if getX is overridden in ColoredPoint?

30 Outline Overloading Inheritance Subtyping Overriding  Hiding

31 Hiding Fields and Class Methods  Def. Hiding Refers to the introduction of a field (instance or class) or a class method in a subclass that has the same name as a field or class method declared in the superclass.  Hiding vs. overriding Statically resolved (bound) at compile-time vs. dynamically dispatched at run-time

32 Example class Student { protected String description = “Student”; public String getDescription() { return description; } class Undergraduate extends Student { protected String description = “Undergraduate”; } new Student().getDecription(); // what value is returned? new Undergraduate().getDescription(); // what value? Q. How to refer to hidden fields? hiding of field