DATA STRUCTURES Lecture: Inheritance Slides adapted from Prof. Steven Roehrig.

Slides:



Advertisements
Similar presentations
OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
Advertisements

DATA STRUCTURES Lecture: Interfaces Slides adapted from Prof. Steven Roehrig.
Programmer-defined classes Part 2. Topics Returning objects from methods The this keyword Overloading methods Class methods Packaging classes Javadoc.
DATA STRUCTURES Lecture: Initialization & Cleanup Slides adapted from Prof. Steven Roehrig.
Intermediate Java Sakir YUCEL MISM/MSIT Carnegie Mellon University Lecture: Access Control & Reuse Slides adapted from Prof. Steven Roehrig.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
Object-Oriented Programming MISM/MSIT Carnegie Mellon University Lecture 4: Polymorphism.
Road Map Introduction to object oriented programming. Classes
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 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
Object-Oriented Programming MISM/MSIT Carnegie Mellon University Lecture 4: Access Control & Reuse.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 3 Object Oriented Programming in Java Language Basics Classes,
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 04 / 21 / 2010 Instructor: Michael Eckmann.
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
MIT AITI 2003 Lecture 7 Class and Object - Part I.
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,
CS 106 Introduction to Computer Science I 04 / 13 / 2007 Friday the 13 th Instructor: Michael Eckmann.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
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.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
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.
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 5, page 1 Sun Certified Java 1.4 Programmer Chapter 5 Notes Gary Lance
CIT 590 Intro to Programming First lecture on Java.
Object-Oriented Programming Instructor: Peyman Dodangeh Sharif University of Technology Lecture 4: Access Control & Reuse andrew.cmu.edu/user/syucel/Java/lectures.html.
C# F 1 CSC 298 Object Oriented Programming (Part 1)
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Programming in Java CSCI-2220 Object Oriented Programming.
DATA STRUCTURES Lecture: Polymorphism Slides adapted from Prof. Steven Roehrig.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
JAVA COURSE 1 Computer Engineering Association. Compile your first program Public class Hello{ public class Hello(){ System.out.println(“Hello”); } puclic.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Inheritance (Part 2) Notes Chapter KomondorBloodHound PureBreedMix Dog Object Dog extends Object PureBreed extends Dog Komondor extends PureBreed.
Inheritance and Access Control CS 162 (Summer 2009)
Lecture 10 Concepts of Programming Languages Arne Kutzner Hanyang University / Seoul Korea.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Inheritance (Part 2) KomondorBloodHound PureBreedMix Dog Object.
Sadegh Aliakbary Sharif University of Technology Spring 2011.
Reusing Classes composition The trick is to use the classes without soiling the existing code. In this chapter you’ll see two ways to accomplish.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
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.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 4 is due Nov. 20 (next Friday). After today you should know everything you need for assignment.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Classes, Interfaces and Packages
Access Specifier. Anything declared public can be accessed from anywhere. Anything declared private cannot be seen outside of its class. When a member.
Object-Oriented Programming Dr. Ramzi Saifan Slides adapted from Prof. Steven Roehrig.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Chapter 7 Classes and Methods III: Static Methods and Variables Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition)
Basic Object-Oriented concepts. Concept: Classes describe objects Every object belongs to (is an instance of) a class An object may have fields –The class.
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.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 6 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
BY:- TOPS Technologies
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
OOP: Encapsulation &Abstraction
Inheritance and Polymorphism
OBJECT ORIENTED PROGRAMMING II LECTURE 8 GEORGE KOUTSOGIANNAKIS
Java Programming Language
Lecture 10 Concepts of Programming Languages
Presentation transcript:

DATA STRUCTURES Lecture: Inheritance Slides adapted from Prof. Steven Roehrig

Today’s Topics Implementation hiding with packages and access specifiers. Composition Inheritance More on constructors Finals Class loading 2

Access Specifiers public, protected, private and “friendly” main() needs to be public, so the runtime system can call it. toString() needs to be public since it is public in Object, and we are “overriding” it. 3

The “Need To Know” Principle Like military secrets, portions of your classes are best kept private. The public interface of a class should provide everything users need, but nothing they don’t. Access specifiers allow you to enforce the “need to know” principle. 4

Access Specifiers public members (variables and methods) are freely available for anyone’s use. private members can be accessed (used) only by the methods of the containing class. protected members are public to subclasses, private to others. “Friendly” members have package access: no access specifier public within the containing package 5

Packages Java’s concept of “module”. A group of related classes. A package can have a name, but there is the unnamed package, which holds all the classes in your program that you haven’t put into a named package. 6

How Does It All Work? So far, we haven’t used packages and access specifiers. Why has this worked? We kept all our.class files in the same folder; they are in the unnamed package. All of our members were therefore friendly. Only methods that are called from another package need access specifiers. Make sure you have the current directory (‘.’) in your classpath. 7

The Basic Rules Class members should be private unless there is a need to know or use. Think carefully about the public interface. Use accessors/mutators (aka get and set methods) to control access to private member variables. Often we create methods that are only used internally; make these private. We’ll worry about protected later. 8

Example public class Fraction { public Fraction() public Fraction(int n, int d) public String toString() public String toDecimal() public Fraction add(Fraction f) private int numerator; private int denominator; private int gcd(int a, int b) } 9

How To Change A Fraction? This is a design decision. Some classes are “immutable” for good (or bad!) reasons. String is an example. If we want users to change a Fraction object’s values, provide a “set” function: public void set(int n, int d) { // test carefully for suitability, then: numerator = n; denominator = d; } 10

Interface vs. Implementation For flexibility, we want the right to change an implementation if we find a better one. But we don’t want to break client code. Access specifiers restrict what clients can rely on. Everything marked private is subject to change. 11

Example: NNCollection Our clients want to store last names and associated telephone numbers. The list may be large. They want a class NameNumber for name & number pairs NNCollection() insert(NameNumber) findNumber(String) 12

NameNumber public class NameNumber { private String lastName; private String telNumber; public NameNumber() {} public NameNumber(String name, String num) { lastName = name; telNumber = num; } public String getLastName() { return lastName; } public String getTelNumber() { return telNumber; } 13

NNCollection public class NNCollection { private NameNumber[] nnArray = new NameNumber[100]; private int free; public NNCollection() {free = 0;} public void insert(NameNumber n) { int index = 0; for (int i = free++; i != 0 && nnArray[i-1].getLastName().compareTo(n.getLastName()) > 0; i--) { nnArray[i] = nnArray[i-1]; index = i; } nnArray[index] = n; } 14

NNCollection (cont.) public String findNumber(String lName) { for (int i = 0; i != free; i++) if (nnArray[i].getLastName().equals(lName)) return nnArray[i].getTelNumber(); return new String("Name not found"); } 15

NNCollection Insertion nnArray… Initial Array free nnArray… Insert “Lewis” free Lewis

NNCollection Insertion (cont.) nnArray… i Lewis Insert “Clay” free nnArray… i Lewis free nnArray… Clay free Lewis

Yes, This Is Rotten It uses a fixed-size array. Array elements are interchanged every time a new name is entered. Slow. The array is searched sequentially. Slow. But, our clients can get started on their code. We will go back and build a better implementation. 18

More on Packages Bringing in a package of classes: import java.util.*; Bringing in a single class: import java.util.ArrayList; The compiler can find these things, through the classpath. If we’re working from the command line, the classpath must be an environmental variable. 19

Creating a Package The very first line in all the files intended for the package named myPackage: package myPackage; Put all of the.class files in a directory named myPackage. Put the myPackage directory, as a subdirectory, in a directory given in the classpath. 20

Class Access Classes can be public or not. Non-public classes are available only within the package they are defined in. There can be only one public class in a “compilation unit” (a.java file). Non-public classes are “helper” classes, not for public use. 21

Class Reuse A noble goal, and in Java it’s finally happening! Basically two ways: composition and inheritance. Composition is called “has-a”. Inheritance is called “is-a”. 22

Composition Using instance variables that are references to other objects Have we ever used this? 23

Inheritance An object of a new class that inherits from an existing class has all the “powers and abilities” of the parent class: all data members all methods you can add additional data and methods if you wish a derived class object “is-an” object of the parent class type, so can be used in function calls where a parent-class object is specified 24

Inheritance Syntax class Cleanser { private String activeIngredient; public void dilute(int percent) {// water-down} public void apply(DirtyThing d) {// pour it on} public void scrub(Brush b) {// watch it work} } public class Detergent extends Cleanser { private String specialIngredient; public void scrub(Brush b) { // scrub gently, then super.scrub(b); // the usual way } public void foam() { // make bubbles} } 25

Access Control, Again Detergent does indeed have an activeIngredient, but it’s not accessible. If Detergent needs to access it, it must be either made protected (or friendly) in Cleanser, or be accessible through get and set methods in Cleanser. You can’t inherit just to get access! 26

What Is A Detergent Object? An object of type Cleanser, having all the members of Cleanser. An object of type Detergent, having all the additional members of Detergent. An object that “responds” to “messages” (ummm…method calls) as though it’s a Cleanser, unless new methods have been added to Detergent, or Cleanser methods have been over-ridden. 27

Subclasses and Constructors Think of a Detergent object as containing a Cleanser sub-object. So, that sub-object has to be constructed when you create a Detergent object. The Cleanser object has to be created first, since constructing the remaining Detergent part might rely on it. “Always call the base class constructor first.” 28

Subclasses and Constructors class Cleanser { private String activeIngredient; Cleanser() { System.out.println(“Cleanser constructor”); } public class Detergent extends Cleanser { private String specialIngredient; Detergent() { System.out.println(“Detergent constructor”); } public static void main(String[] args) { Detergent d = new Detergent(); } 29

Subclasses and Constructors class Cleanser { private String activeIngredient; Cleanser(String active) { activeIngredient = active; } public class Detergent extends Cleanser { private String specialIngredient; Detergent(String active, String special) { super(active); // what if this isn’t here? specialIngredient = special; } 30

Composition vs. Inheritance Think “has-a” vs. “is-a”. Consider the NNCollection class. Suppose now we need to store a String/int pair (names and ages, perhaps). Should we inherit, or compose? In either approach, we just need to be able to turn Strings into ints, and vice versa (not hard). 31

Composition vs. Inheritance class NACollection { private NNCollection nnc; NACollection() { // …} public void insert (NameAge n) { uses nnc’s insert()} public int findAge(String name) { uses nnc’s findNumber()} } or class NACollection extends NNCollection { NACollection() { //…} public void insert(NameAge n) { uses super.insert()} public int findAge(String name) { uses super.findNumber()} } 32

protected Class Members public to subclasses. private to “the outside world”, except within the package (i.e., they are “friendly”) private is usually the best policy, unless you are looking for speed (but then why use Java!?). 33

Upcasting class CellPhone { cellPhone() { //…} public void ring(Tune t) { t.play(); } } class Tune { Tune() { // …} public void play() { // …} } class ObnoxiousTune extends Tune{ ObnoxiousTune() { // …} // … } 34

An ObnoxiousTune “is-a” Tune class DisruptLecture { public static void main() { CellPhone noiseMaker = new CellPhone(); ObnoxiousTune ot = new ObnoxiousTune(); noiseMaker.ring(ot); // ot works though Tune called for } Tune ObnoxiousTune A “UML” diagram 35

The final Keyword Vaguely like const in C++. It says “this is invariant”. Can be used for data methods classes A kind of protection mechanism. 36

final Data (Compile-Time) For primitive types (int, float, etc.), the meaning is “this can’t change value”. class Sedan { final int numDoors = 4; For references, the meaning is “this reference must always refer to the same object”. final Engine e = new Engine(300); 37

final Data (Run-Time) Called a “blank final;” the value is filled in during execution. class Sedan { final int topSpeed; Sedan(int ts) { topSpeed = ts; // … } class DragRace { Sedan chevy = new Sedan(120), ford = new Sedan(140); //! chevy.topSpeed = 150; 38

final Method Arguments class Sedan { public void replaceTire(final Tire t) { //! t = new Tire(); Same idea: a final primitive has a constant value a final reference always refers to the same object. Note well: a final reference does not say that the object referred to can’t change (cf. C++) 39

final Methods final methods cannot be overridden in subclasses. Maybe a bad idea? final methods can be inlined, allowing the compiler to insert the method code where it is called. This may improve execution speed. Only useful for small methods. private methods are implicitly final. 40

final Classes These can’t be inherited from (ummm, “subclassed”?. All methods are implicitly final, so inlining can be done. 41