Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and.

Slides:



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

Introduction to Java 2 Programming
More on Classes Inheritance and Polymorphism
OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
1 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
Inheritance Inheritance Reserved word protected Reserved word super
Object Oriented Programming Chapter 7 Programming Languages by Ravi Sethi.
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Creating Classes from Other Classes Chapter 2 Slides by Steve Armstrong LeTourneau University Longview, TX  2007,  Prentice Hall.
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 and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
Encapsulation, Inheritance & Interfaces CSE 115 Spring 2006 February 27, March 1 & 3, 2006.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Chapter 7 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
ObjectDraw and Objects Early Chris Nevison Barbara Wells.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
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.
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.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
CS200 Algorithms and Data StructuresColorado State University Part 4. Advanced Java Topics Instructor: Sangmi Pallickara
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.
OOP: Encapsulation,Abstraction & Polymorphism. What is Encapsulation Described as a protective barrier that prevents the code and data being randomly.
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.
Object Oriented Software Development
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Object Oriented Programming
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
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.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Classes, Interfaces and Packages
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
Defining Classes I Part B. Information hiding & encapsulation separate how to use the class from the implementation details separate how to use the class.
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.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
CSCE 240 – Intro to Software Engineering Lecture 3.
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.
9.1 CLASS (STATIC) VARIABLES AND METHODS Defining classes is only one aspect of object-oriented programming. The real power of object-oriented programming.
 The word static is used to declare either a ________ variable or method.  Why do we use statics?  What is Polymorphism? class In general, we use a.
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: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
7.1 What Is An Object Object-oriented program - Description or simulation of application Object-oriented programming is done by adopting or extending an.
Inheritance and Polymorphism
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Object Oriented Programming
Inheritance, Polymorphism, and Interfaces
OBJECT ORIENTED PROGRAMMING II LECTURE 8 GEORGE KOUTSOGIANNAKIS
Inheritance, Polymorphism, and Interfaces. Oh My
Week 6 Object-Oriented Programming (2): Polymorphism
Java Inheritance.
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Fundaments of Game Design
Defining Classes and Methods
Review of Previous Lesson
Final and Abstract Classes
Presentation transcript:

Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and Murtagh CS 120 Lecture November 2012

2 Shared Features Common to define classes that share features –FilledRect and FramedRect Desirable to let classes with common features and behaviors share code –saves programmer time –improves code reliability

3 Inheritance mechanism that provides means to share code in related classes already familiar...sort of –classes that extend WindowController inherit variables and other features from WindowController canvas, getContentPane(), and others defined in WindowController class

4 Extension as Specialization a class that extends another is a subclass a class that is extended is a superclass inheritance describes relationship between a subclass and superclass –subclass inherits features from superclass it extends –subclass will include every method and instance variable in superclass –subclass may also include new features subclass like the superclass- but more special or specialized

5 An Interactive Card Game Note the small framed display areas in this game interface

6 Framed Displays current score“lives remaining” time remainingstart message

7 Design Choices Could define independent class for each category of frame or Better: –define class describing empty frame –extend it to define classes of specialized frames

8 Using extends Say we want to display text in a frame A FramedText class –if written from scratch, would repeat much of FramedDisplay –define as an extension of FramedDisplay

9 public class FramedText extends FramedDisplay extends FramedDisplay –tells Java to include all instance variables and methods from FramedDisplay in FramedText –no need to redefine in new class add what we need to manipulate Text object displayed in frame

10 Subclass Constructors often want to –inherit behavior of superclass constructor –but also do more write new constructor –begin with special instruction to invoke constructor of superclass ex. super( x, y, width, height, canvas ); –add statements to perform additional work desired

11 super an invocation of super can only appear as first command in a constructor’s body if invocation of super not included, Java inserts super(); automatically Note: Will result in error if class being extended has no parameterless constructor

12 Methods of subclasses can be used in the usual way. If we have private FramedText welcome; and execute welcome = new FramedText( “Hello”, 20, 20, 100, 30, canvas ); can legally execute welcome.setTextSize( 24 ); and welcome.highlight();

13 Access Control public- can be accessed in other classes private –only accessible within class in which defined –restriction applies even for subclasses; private name defined in superclass cannot be accessed in subclass protected –accessible in classes that extend the one in which name defined

14 Designing for Extension easy to imagine designing subclasses of FramedDisplay that will require info about –dimensions of parts of frame –locations of parts of frame in designing interface for a class, must consider –what methods would be helpful to objects outside of the class –what would be useful to those extending the class prefer protected accessor methods to protected variables –access to protected variables (if not final) allows changes that can lead to errors

15 Inheritance Hierarchies Implement a FramedCounter class –display value of a counter (as in FramedText) –include an increment method FramedCounter inherits features from FramedText –includes features that FramedText inherits from FramedDisplay

16 // A FramedCounter object displays a numeric counter on // a background framed by a distinct border public class FramedCounter extends FramedText { private int counter = 0;// Current value of counter // Create a FramedCounter object displaying 0 // at the position and with the dimensions specified public FramedCounter( double x, double y, double width, double height, DrawingCanvas canvas ) { super( “0”, x, y, width, height, canvas ); } // Increase the counter’s value and update display public void increment( int amount ) { counter = counter + amount; message.setText( counter ); positionContents(); }

17 Subclasses and Superclasses A is a superclass of B if –B extends A or –B extends C and A is a superclass of C B is a subclass of A if –B extends A or –B extends C and C is a subclass of A

18 Subclass Type Compatibility Can assign an object to a variable as long as type of object is either –same as type of variable or –a subclass of the variable type

19 Assume these variable definitions FramedDisplay someFrame; FramedText someText; FramedCounter someCounter; The following assignments are legal: someFrame = new FramedDisplay(... ); someFrame = new FramedText(... ); someFrame = new FramedCounter(... ); someText = new FramedText(... ); someText = new FramedCounter(... ); someCounter = new FramedCounter(... );

20 Assuming the variable definitions: FramedDisplay someFrame; FramedText someText; FramedCounter someCounter; The following are also legal: someFrame = someText; someFrame = someCounter; someText = someCounter;

21 Parameter Compatibility Same rules apply Actual parameter compatible with formal parameter as long as –its type is same as type of formal parameter or –its type is a subclass of the formal parameter type

22 Assuming the variable definitions: FramedDisplay someFrame; FramedText someText; FramedCounter someCounter; And a collection class with method: public void addFrame( FramedText someText ) {... the following are legal for an object of the collection type scoreDisplays.addFrame( someText ); scoreDisplays.addFrame( someCounter );

23 what about someCounter = someFrame; someText = someFrame; and scoreDisplays.addFrame( someFrame );

24 what about someCounter = someFrame; someText = someFrame; and scoreDisplays.addFrame( someFrame ); All Illegal

25 Checking Types Consider someFrame = new FramedCounter(... ); someCounter = someFrame; someText = someFrame; scoreDisplays.addFrame( someFrame ); last 3 lines still considered illegal by Java. If programmer confident variable of correct type can introduce type cast someCounter = (FramedCounter) someFrame; To ensure type cast can be done if ( someFrame instanceof FramedCounter ) { someCounter = (FramedCounter) someFrame }

26 Overriding Method Definitions Sometimes need to change behavior of methods in superclass for proper functionality in subclass. –define method in body of subclass with same name –new method is said to override the original method.

27 The Object Class Java class Object is a superclass of all Java classes All classes inherit certain methods from Object –equals: version defined in Object compares using == ; can override to tailor behavior of equals for a class –toString: returns a String describing the object on which it is invoked; often useful to override.

28 Accessing Overridden Methods sometimes want to extend- not totally change- steps performed by a method in a superclass. super as a means to access an overridden method from within a subclass

29 Using super Say we have added a move method to FramedDisplay // Move the parts of the framed display by offsets public void move( double xoff, double yoff ) { border.move( xoff, yoff ); body.move( xoff, yoff ); } Can override this method in FramedText as follows: // Move the display by specified offsets public void move( double xoff, double yoff ) { super.move( xoff, yoff );// Move the body and border positionContents(); }

30 Can refer to any nonprivate method of a superclass with “super.methodname” in the definition of a subclass

31 Dynamic Method Invocation Say we declare private FramedDisplay someFrame; and later execute someFrame = new FramedText( “Follow me”, 50, 50, 80, 25, canvas ); someFrame.move( 100, 50 ); Which version of move is executed? –the version in FramedDisplay? –the version in FramedText?

32 Dynamic Method Invocation Say we declare private FramedDisplay someFrame; and later execute someFrame = new FramedText( “Follow me”, 50, 50, 80, 25, canvas ); someFrame.move( 100, 50 ); Which version of move is executed? –the version in FramedDisplay? –the version in FramedText

33 Java invokes the version of a method associated with an object’s class regardless of the type of name through which it is accessed process of identifying correct method is called dynamic method invocation

34 A More Complex Example Say we define moveTo in FramedDisplay public void moveTo( double x, double y ) { this move( x - border.getX(), y - border.getY() ); } Java interprets this dynamically invocation refers to move method of this, the object whose moveTo was invoked If we execute FramedText welcomeMessage = new FramedText( “Click to begin”,... ); welcomeMessage.moveTo( centerX, centerY ); move in FramedText is used

35 Design Suggestions Sometimes useful to define a method of a superclass with the expectation it will be overridden Consider adding the following to FramedDisplay –move, as before –setWidth, setHeight Subclasses will need to override all of these for correct functionality

36 Better Design Define positionContents method in FramedDisplay: protected void positionContents( ) { } Define move as: // Move the parts of the framed display by offsets public void move( double xoff, double yoff ) { border.move( xoff, yoff ); body.move( xoff, yoff ); positionContents(); } If setWidth and setHeight defined similarly, only positionContents needs to be overridden in subclasses

37 Abstract Classes and Methods Abstract class –provides base for defining useful subclasses –not useful by itself We defined positionContents in FramedDisplay to ensure that subclasses of FramedDisplay would define it Unsatisfying to define an empty method Could replace definition of positionContents with abstract protected void positionContents() ; and make class abstract public abstract class FramedDisplay {...

38 Given the description of a problem, –how do you determine what classes to define? –how do you design each class? Need a design methodology Object-Oriented Design

39 Object-Oriented Design Often software mimics the real world Decompose problem into objects –identify properties and behaviors –model in software

40 Abstraction An object provides an abstraction –can use without knowing details of its implementation –abstract away details; understand at higher level Follows from our use of objects in real world –can use a stopwatch without knowing exactly how it works Well-designed classes provide good abstractions.

41 Encapsulation notion of taking variables and data structures and wrapping them inside a class definition Information Hiding notion of hiding details of implementation as much as possible Eg. Users of our Triangle class don’t need to know HOW it stores the triangle.

42 Why Important? protects variables from being modified inappropriately by other classes can present classes to others for use by simply specifying interface ex. You used objectdraw library without knowing any implementation details! can change details of class definition without affecting those using it.

43 Writing Comments Each class should have a class comment –Description of class –Author’s name and date Each constant and variable should be commented –describe purpose (what, not how!) –parameters –return value, if any For long/complex methods –include comments in method –explain what is happening –balance clarity and brevity

Student To Do’s HW10 –Green Screen program. –Review Lab 10 to get started. –There is a grading criteria, check it! Includes both style and commenting –Try to get your web page online. Java Project – –Due 12/12 Practice examples on your own! 44