Chapter 13 Abstraction and inheritance. This chapter discusses n Implementing abstraction. u extension u inheritance n Polymorphism/dynamic binding. n.

Slides:



Advertisements
Similar presentations
Final and Abstract Classes
Advertisements

More on Classes Inheritance and Polymorphism
Object Oriented Programming with Java
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.
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.
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
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,
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.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
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.
Chapter 10 Classes Continued
Polymorphism. Lecture Objectives To understand the concept of polymorphism To understand the concept of static or early binding To understand the concept.
Chapter 11: Inheritance and Polymorphism Java Programming: Program Design Including Data Structures Program Design Including Data Structures.
Inheritance using Java
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.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
Chapter 12 Inheritance and Exceptions Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas,
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
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.
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
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.
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.
Coming up: Inheritance
OOP: Inheritance. Inheritance A class can extend another class, inheriting all its data members and methods while redefining some of them and/or adding.
Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism.
Inheritance and Subclasses CS 21a. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L16:
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Inheritance and Polymorphism. Superclass and Subclass Inheritance defines a relationship between objects that share characteristics. It is a mechanism.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
Inheritance and Polymorphism
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
Notices Assn 2 is due tomorrow, 7pm. Moodle quiz next week – written in the lab as before. Everything up to and including today’s lecture: Big Topics are.
Inheritance a subclass extends the functionality of a superclass a subclass inherits all the functionality of a superclass don't reinvent the wheel – "stand.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Java Programming Fifth Edition Chapter 9 Introduction to Inheritance.
Class Inheritance Part II: Overriding and Polymorphism Corresponds with Chapter 10.
An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 10 : Inheritance.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Modern Programming Tools And Techniques-I
Chapter 11 Inheritance and Polymorphism
Inheritance and Polymorphism
Chapter 11: Inheritance and Polymorphism
Chapter 3 Inheritance © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
Object Oriented Programming
Chapter 9 Inheritance and Polymorphism
Inheritance Chapter 7 Chapter 7.
Java Programming Language
Java Inheritance.
Advanced Inheritance Concepts
Chapter 8 Class Inheritance and Interfaces
Final and Abstract Classes
Presentation transcript:

Chapter 13 Abstraction and inheritance

This chapter discusses n Implementing abstraction. u extension u inheritance n Polymorphism/dynamic binding. n Javas accessibility and scoping rules.

To abstract is to eliminate distinctions n Two things which are different at one level are similar or equivalent at a more abstract level. n Upper classes are more abstract; lower classes are more concrete. n The more concrete "subclass" extends the more abstract "superclass" and inherits the functionality of the superclass. n The abstract class generalizes or abstracts the concrete class.

extends is-a is a subclass of is a descendant of generalizes is an abstraction of is a superclass of is an ancestor of Circle extends Figure etc. Circle ClosedFigure

Maze Example n A Portable is something that the explorer can pick up, carry, and put down. n A PortableList describes the collection of items the explorer is carrying.

Extension and inheritance n Class extension: the mechanism provided by the language for implementing abstraction. n Inheritance: a mechanism by which a subclass automatically possesses all of the non-private features of its superclass.

Extension and inheritance (cont.) public class ClosedFigure{ public Location getLocation () { return this.location; } public void setLocation (Location newLocation) { this.location = newLocation; } private Location location; }

Extension and inheritance (cont.) public class Circle extends ClosedFigure { … public int radius (){ … } Circle c = new Circle(10); Location l = c.getLocation(); int d = c.radius();

Extension and inheritance (cont.) n A subclass does not inherit private features of its superclass. The variable location is private to ClosedFigure. Illegal: this.location = null; Legal: this.setLocation(null);

Generalization and subtyping n A reference to a subclass is also considered a reference to its superclass. i.e. a reference to a Circle can be considered a reference to a ClosedFigure. n The type reference-to-Circle is a subset of the type reference-to-ClosedFigure.

Circle c = new Circle(10); ClosedFigure f; f = c;

Generalization and subtyping (cont.) n A ClosedFigure cannot be treated as a Circle. int d; Location l; l = f.getLocation();//legal d = f.radius();//Illegal c = f;//Illegal

Generalization and subtyping (cont.) Suppose we want to get subclass information from f. First check to make sure it is the correct descendant and then cast the object f to the inheriting class. if (f instanceof Circle) { Circle c = (Circle) f; d = c.radius(); … } n subtyping: a mechanism by which an instance of a subclass can be used in any context specifying the superclass.

Abstract class n A class that is not intended to be instantiated should be declared as abstract. n Instances of an abstract class cannot be created. n It serves as a foundation on which to build subclasses. n Non-abstract classes are called concrete.

Abstract classes (cont.) public abstract class ClosedFigure {… n We cannot instantiate an abstract class, but we can define variables that reference the class. ClosedFigure f; f = new ClosedFigure(); //Illegal f = new Circle(10);//Legal.

Abstract methods n Abstract classes may have abstract methods. An abstract method is specified, but not implemented. n Since an abstract method cannot be implemented in the abstract class, any concrete subclass must provide an implementation for any abstract method it inherits. public abstract class ClosedFigure { public abstract int area(); … }

Abstract methods (cont.) int d = f.area();//Legal. If f references a Circle when the statement is executed, f.area() is directed to a Circle. If f references a rectangle when the statement is executed, f.area() is directed to a Rectangle. n This mechanism is called polymorphism, dynamic binding, or dispatching.

Constructors n Constructors are not inherited. n The constructor is responsible for initializing components defined in a superclass as well as those expressly defined in the class itself. n A superclass constructor can be called: super(arguments);

Constructors (cont.) public class Circle extends ClosedFigure { public Circle (int radius) { super(); myRadius = radius; } public Circle () { this(1); //invoke above constructor } … private int myRadius; }

Constructors (cont.) If no constructor is called for a superclass, and no constructor of the same class is called, the constructor is assumed to begin with the invocation of the superclass constructor super(); public Circle (int radius) { super(); //assumed myRadius = radius; }

Constructors (cont.) n If a class doesnt contain a constructor definition, a default constructor requiring no arguments is provided automatically. public Class () { super(); } The key words this and super as constructor invocations can appear only as the first statement of another constructor.

Overriding and polymorphism Every Java class comes equipped with a method equals (Object obj). n This is because every class is a subclass of Object. n A class can redefine a method that it inherits. n Overriding: providing an alternative implementation of an inherited method.

Overriding and polymorphism (cont.) The redefined method must have the same return type and the same number and type(s) of parameters as the inherited method. public class Circle extends ClosedFigure { … public boolean equals (Object c) { if (c instanceof Circle) return this.radius() ==((Circle)c).radius(); else return false; } … }

Overriding and polymorphism (cont.) ClosedFigure f1; ClosedFigure f2; int n; // n is given a value here if (n==0) { f1 = new Circle(); f2 = new Circle(); } else { f1 = new Rectangle(); f2 = new Rectangle(); } boolean b = f1.equals(f2);

Overriding and polymorphism (cont.) n polymorphism: dynamic behavior by which the method performed as the result of a call to a given object is determined at run-time by the class of the object. n A class that overrides a method can call its parents overridden method. public boolean equals (Object c) { if (c instanceof ColoredCircle) return super.equals(c) && this.colored().equals(c.color()); else return false; }

Method overloading n A class can contain distinct methods with the same name as long as these methods differ in number, order, or type(s) of parameters. n This is called overloading. public int m (int x); public int m (Object obj); public void m (int x, int y); public void m (Object obj, int x); public void m (int x, Object obj); public Object m (int i); //Illegal

Method overloading (cont.) public class Circle extends ClosedFigure { … public boolean equals (Object obj) { … } public boolean equals (Circle c) { return this.radius() == c.radius(); } n Overloading inherited methods can lead to confusion: ClosedFigure f = new Circle (); Circle c = new Circle (); boolean b1 = f.equals(c); //c is type Circle boolean b2 = c.equals(f); //f is ClosedFigure boolean b3 = c.equals((Circle)f );//(Circle) f // is a Circle

Method overloading (cont.) n Overloaded methods are different methods in the same class. n Overriding involves providing different implementations for a method in different classes.

Subclasses and contracts n When overriding a method, postconditions can be strengthened but cannot be weakened. public void fill (Color c) Paint this ClosedFigure with the specified Color require: c != null ensure: this.backgroundColor().equals(c)

Subclasses and contracts (cont.) public class MonochromeFigure extends ClosedFigure { … /** * Paint this MonochromeFigure black or white *require: * c.equals(Color.WHITE) || * c.equals(Color.BLACK) */ public void fill (Color c) { Require.condition( c.equals(Color.WHITE) || c.equals(Color.BLACK)); …} }

Identifying common functionality n The reason that we group classes together is because they have common attributes or functions. Suppose all the items that a maze game explorer can carry have weight ; make weight a feature of the class Portable. public abstract class Portable { … public int weight () … }

Identifying common functionality (cont.) public class Pack { … public int totalweight () { int sum = 0; int i = 0; while (i < items.size()) { sum = sum + items.get(i).weight(); i = i +1; } return sum; } … private PortableList items; }

Alternative implementation for a method (cont.) n We will extend the class Player from the nim game to include a PerfectPlayer that wins whenever possible. PerfectPlayer overrides the makeMove method. n The creation of a new subclass does not require changes in a Player client.

Refining the implementation n We override the method so that the subclass performs some action in addition to what is done in the superclass. n The subclass, in overriding the method, also invokes the superclass method in the overriding definition. public class Wizard extends Explorer { … public void addToPack (Portable item) { item.removeCurses(); super.addToPack(item); } … }

Refining the implementation (cont.) n General format: do something before call the superclass method do something after

Extending functionality n Inheritance is used commonly to extend the functionality of a class. n Example: We could extend the Player class of nim to include keeping score (the number of games Player has won). n Sometimes additional functionality involves overriding existing methods.

Extending functionality (cont.) n Example: Define a nim Player whose move is set by a client: class dummyPlayer extends Player { /** * Set number of sticks taken */ public void setNumber (int n) … /** * Take number of sticks specified */ public void makeMove (Pile pile, int maximum) … }

Feature accessibility n So far, the methods defined in a class have been either public or private. n Features call also be protected or restricted. n Feature access has to do with the structure of the program text and not with the run-time state of the system; from where in the program text can this feature be accessed?

Feature accessibility (cont.) public class Circle { … public boolean equals (Object obj) { if (obj instanceof Circle) { return myRadius == ((Circle)obj).myRadius; /* the private component myRadius of the argument is being accessed */ else return false; } //legal functionality … private int myRadius; }

Feature accessibility (cont.) public class ColoredCircle extends Circle{ … public boolean equals (Object obj) { if (obj instanceof ColoredCircle){ return myRadius == ((Circle)obj).myRadius && myColor == ((ColoredCircle)obj).myColor; else return false; } /* illegal functionality; neither of the references to myRadius is legal */ … private int myColor; }

public boolean equals (Object obj) { if (obj instanceof ColoredCircle) { return this.radius() == ((Circle)obj).radius() && myColor == ((ColoredCircle)obj).myColor; else return false; }//LEGAL FUCNTIONALITY Feature accessibility (cont.)

Feature accessibility limited by class accessibility n A class that is not public can be accessed only from within its own package. n If a class is not visible outside its package, then neither are its features. n Even if features are labeled public, access to features of a non-public class is limited to the package containing the class definition.

Protected features n Private features of a class are not directly accessible in a subclass. n A class inherits a feature specified as protected, and the feature is accessible in the class. The class Player has a component numberTaken. n If this component is labeled protected, then subclasses like PerfectPlayer can access the variable directly. protected int numberTaken;

Protected features (cont.) /** * This example is in the context of * numberTaken being private. */ public void makeMove (Pile pile, int maximum) { int size = pile.size(); int number; if (numberToTake <= size && numberToTake <= maximun) number = numberToTake; else if (size <= maximum; number = size; else number = maximum pile.remove(number); this.numberTaken = number; //illegal access } // numberTaken is private

Protected features (cont.) One approach: protected int numberTaken; n Better approach: protected void setNumberTaken (int number){ numberTaken = number; } … private int numberTaken;

Protected features (cont.) n The accessibility of a protected feature is rather broad. n Class BClass or CClass can directly access any protected variables in AClass.

Protected features (cont.) n Any class that inherits from or is in the same package as a class has access to the protected variables.

Protected features (cont.) n A better approach is to make the component private, and allow controlled access through protected methods.

Restricted features n If a feature is declared neither public, protected, nor private, it is considered restricted. n There is no keyword restricted. n Any class in the same package has access to restricted variables. n If a feature is neither public nor private, the maintenance programmer must determine why this is so, and must assure that any use of the feature does not compromise the system. n Misuse of feature accessibility leads to architectural drift or architectural erosion, and the system becomes brittle.

Java scoping rules n An identifier may occur many times in a program in many different contexts. n An identifier can be introduced as the name of a variable, method, or parameter in a variable definition, method definition, or parameter specification. public void takeHit (int hitStrength) private int tally; int temp;

Java scoping rules (cont.) n A defining occurrence establishes the identifier as the name of some entity. n An applied occurrence is the use of an identifier to refer to the thing it names. tally = tally + 1; n An applied occurrence sometimes is prefixed with an object reference. this.room = monster.location();

Java scoping rules (cont.) Scoping rules are language rules that associate applied identifier occurrences with defining occurrences. public void increment () { tally = tally +1; } … private int tally; …

Java scoping rules (cont.) n The scope of a local variable definition is from the definition to the end of the compound statement ({ }) or method body containing the definition. n A parameter is treated like a local variable defined just inside the method body. public boolean smallerThan (Rectangle r) { double myArea; double yourArea; myArea = PI*radius*radius; yourArea = r. length() * r.width(); return myArea < yourArea; }

Java scoping rules (cont.)

public boolean smallerThan (Rectangle R){ double area1 = 100.0; double area2 = area1;//in scope of area1 } public boolean smallerThan (Rectangle R){ double area1 = area2;//NOT in scope double area2 = 100.0; }

Java scoping rules (cont.)

n An automatic variable can hide a component variable with the same name. public class Circle { … public void setRadius (int radius){ this.radius = radius; //this.radius-- component variable //radius -- automatic variable } … private int radius; }

Weve covered n Fundamental methods of modeling with objects: abstraction via class extension. u subclasses u extending functionality n Subtyping n Polymorphism n Public, private, protected, and restricted features. n Java scoping rules.

Glossary

Glossary (cont.)