Session 6 Comments on Lab 3 & Implications of Inheritance.

Slides:



Advertisements
Similar presentations
Topic 10 Java Memory Management. 1-2 Memory Allocation in Java When a program is being executed, separate areas of memory are allocated for each class.
Advertisements

INHERITANCE BASICS Reusability is achieved by INHERITANCE
Written by: Dr. JJ Shepherd
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
ITEC200 – Week03 Inheritance and Class Hierarchies.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Object Oriented Programming.  OOP Basic Principles  C++ Classes  September 2004  John Edgar 22.
1 Scenario: Audio Clip Imagine that your application played an audio clip Based on user action, a different audio clip may begin playing You want only.
Chapter 10 Classes Continued
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
OOP Languages: Java vs C++
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Computer Science II 810:062 Section 01 Session 2 - Objects and Responsibilities.
OOPs Object oriented programming. Based on ADT principles  Representation of type and operations in a single unit  Available for other units to create.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Session 5 More on Java Strings and Files & Intro. to Inheritance.
Chapter 11 Introduction to Classes Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
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.
Implications of Inheritance COMP204, Bernhard Pfahringer.
Programming Languages and Paradigms Object-Oriented Programming.
Question of the Day  On a game show you’re given the choice of three doors: Behind one door is a car; behind the others, goats. After you pick a door,
CSC 142 Computer Science II Zhen Jiang West Chester University
Java Objects and Classes. Overview n Creating objects that belong to the classes in the standard Java library n Creating your own classes.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l 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.
Object-Oriented Design CSC 212. Announcements This course is speeding up and we are starting new material. Please see me if you feel this is going too.
Programming in Java CSCI-2220 Object Oriented Programming.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Programming Paradigms Lecturer Hamza Azeem. What is PP ? Revision of Programming concepts learned in CPLB Learning how to perform “Object-Oriented Programming”
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Session 22 Chapter 11: Implications of Inheritance.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
CS451 - Lecture 2 1 CS451 Lecture 2: Introduction to Object Orientation Yugi Lee STB #555 (816) * Acknowledgement:
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
Object-Oriented Programming Chapter Chapter
 Objects versus Class  Three main concepts of OOP ◦ Encapsulation ◦ Inheritance ◦ Polymorphism  Method ◦ Parameterized ◦ Value-Returning.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science Iowa State University Office: Atanasoff.
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.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Written by: Dr. JJ Shepherd
Session 7 Introduction to Inheritance. Accumulator Example a simple calculator app classes needed: –AdderApp - contains main –AddingFrame - GUI –CloseableFrame.
Computer Science II 810:062 Section 01 Session 2 - Objects and Responsibilities.
Object Oriented Programming Session # 03.  Abstraction: Process of forming of general and relevant information from a complex scenarios.  Encapsulation:
Chapter 7 Classes and Methods III: Static Methods and Variables Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition)
OOP Basics Classes & Methods (c) IDMS/SQL News
Lecture 12 Implementation Issues with Polymorphism.
Session 7 More Implications of Inheritance & Chapter 5: Ball World Example.
COMPUTER SCIENCE & TECHNOLOGY DEGREE PROGRAMME FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UVA WELLASSA ‏ Properties of Object Oriented Programming.
9.1 CLASS (STATIC) VARIABLES AND METHODS Defining classes is only one aspect of object-oriented programming. The real power of object-oriented programming.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Inheritance a subclass extends the functionality of a superclass a subclass inherits all the functionality of a superclass don't reinvent the wheel – "stand.
C11, Implications of Inheritance
Java Memory Management
Inheritance ITI1121 Nour El Kadri.
Java Memory Management
Inheritance and Polymorphism
Interfaces and Inheritance
Extending Classes.
Chapter 11: More on the Implications of Inheritance
CMSC 202 Constructors Version 9/10.
Presentation transcript:

Session 6 Comments on Lab 3 & Implications of Inheritance

Accumulator Example a simple calculator app classes needed: –AdderApp - contains main –AddingFrame - GUI –CloseableFrame - allows X button –Accumulator - internal representation and implementation of the accumulator

Refactoring Accumulator public void plus() { currentSum+=currentNumber; prepareForNextNumber(); } public void minus() { currentSum-=currentNumber; prepareForNextNumber(); } private void prepareForNextNumber() { currentNumber=0; displayNumber=currentSum; } public int getDisplay() { return displayNumber; } } // end class AccumulatorV2 public class AccumulatorV2 { private int currentSum; private int currentNumber; private int displayNumber; public Accumulator() { clear(); } public void clear() { currentSum=0; currentNumber=0; displayNumber=0; } public void addDigit( int digit ) { currentNumber=currentNumber*10+digit; displayNumber=currentNumber; }

Alternative structure of the program But another way to structure this program would be to create a relationship which is “wide and shallow” –AdderApp creates an an instance of Accumulator which it passes to an instance of AddingFrame. public class AdderApp { public static void main( String[] args ) { Accumulator a = new Accumulator(); AddingFrame f = new AddingFrame(a); f.show(); } // end main } // end class AdderApp –This is a good example of composition. We emphasize that AddingFrame is composed of an Accumulator –This is a good example of writing code that is modular. Now that we know the composition relation, we can compose solutions using variations of Accumulator.

CountedAccumulator Solution public class CountedAccumulator extends Accumulator { private int numberOfOperations; public CountedAccumulator() { super();// calls the superclass’ constructor numberOfOperations=0; } public void plus() { super.plus(); numberOfOperations++; } public void minus() { super.minus(); numberOfOperations++; } public int getOperations() { return numberOfOperations; } } // end class CountedAccumulator

CountedAccumulator Solution Now, before we can really work with this we need to modify other files in our application. We need to set up the AddingFrame so that it works with a CountedAccumulator rather than a regular Accumulator. We do this in the AdderApp class for simplicity. Accumulator a = new CountedAccumulator(); AddingFrame f = new AddingFrame(a);

A solution Why do we do this in the AdderApp rather than leave it alone and modify the AddingFrame? –Because in the end this makes our AddingFrame slightly more versatile. –Think about it...AddingFrame works with an Accumulator (or CountedAccumulator). If one is provided, it uses it. If one is not provided, it creates it. –THAT, is more versatile than telling an AddingFrame to now always create a CountedAccumulator.

Lab 3 Exercise Create a class named EvenOddAccumulator that subclasses Accumulator to implement this behavior. EvenOddAccumulators respond to all the same messages as regular Accumulators. But, in response to plus() and minus() messages, an EvenOddAccumulator both computes the new sum and writes a congratulatory message if the sum is even.

Toward a Solution Here is the critical new piece of the EvenOddAccumulator class: if ( currentSum % 2 == 0 ) { System.out.println( "Hurray! You made an even number." ); } The big question is, what else is a part of the class?

Toward a Solution Here where I thought you would get into trouble during Lab 3 yesterday…

A Problem Accessing Inherited Data $ javac EvenOddAccumulator.java EvenOddAccumulator.java:17: currentSum has private access in Accumulator if ( currentSum % 2 == 0 ) ^ EvenOddAccumulator.java:24: currentSum has private access in Accumulator if ( currentSum % 2 == 0 ) ^ 2 errors Oops! currentSum is declared as a private instance variable in class Accumulator. private means private: no code outside the Accumulator class can access that variable.

A Possible Solution for Accessing Inherited Data Change currentSum to be public or protected. public class Accumulator { protected int currentSum;... }

A Better Solution for Accessing Inherited Data (2) Add a protected “accessor” method to the Accumulator class. Use that method to access the currentSum instance variable in the subclass. public class Accumulator {... protected int getCurrentSum() { return currentSum; } Then use getCurrentSum() in EvenOddAccumulator.

Programming with Inheritance Inheritance is an object-oriented programming construct that enables us to add behavior to an existing system without modifying the existing classes.

Programming with Inheritance Our new EvenOddAccumulator class adds behavior to a program that uses Accumulators without modifying: the behavior of the existing Accumulator class or the existing AddingFrame class! That means... No chance of introducing an unnecessary, unexpected errors into the working Accumulator class. No need to modify programs that use instances of Accumulator but which don’t need instances of EvenOddAccumulator. The ability to use EvenOddAccumulators in programs that expect to use Accumulators.

Programming with Inheritance We could have achieved some of these results without using inheritance by creating a new class named EvenOddAccumulator that simply duplicated the behavior of existing Accumulator class. Using inheritance means that... No need to reimplement existing methods. No need to duplicate code. One of the most important features of object-oriented programming is that it encourages us to create new classes that reuse existing code as much as possible. Without inheritance, you have only one tool for doing that, composition. With inheritance, you have two tools.

Polymorphism polymorphism comes from the Greek root for “many shapes” polymorphism is about how we can use different objects in the same place in our program, i.e., polymorphism depends on objects that are substitutable for one another A polymorphic variable can hold many different types of values Object-oriented languages often restrict the types of values to being subclasses of the declared type of the variable.

Polymorphic Variables in Java Java achieve polymorphic variables by two ways: 1)Interfaces: a variable defined using an interface can hold an object of any class implementing that interface, e.g., in MemoPad, “MemoDatabase datebase” could be assigned either a DefaultMemoDatabase or MyMemoDatabase object. 2)Inheritance: a variable defined using a superclass can hold any instance of a subclass, e.g., in AdderApp: public class AdderApp { public static void main( String[] args ) { Accumulator a = new CountedAccumulator(); AddingFrame f = new AddingFrame(a); f.show(); } // end main } // end AdderApp

Implications of Inheritance/Polymorphism At compile-time, the amount of memory for polymorphic variables cannot be determined, so all objects reside in the heap Because values reside in the heap, reference semantics is used for assignment and parameter passing Most natural interpretation of equality is identity. Since programmers often require a different meaning two operators are needed Garbage collection needed since it is hard for a programmer to know if/when an object is no longer referenced

Typical Memory Layout Program Global variables Stack Heap

Stack-based Memory Objects are stored on the heap When a method is called, an activation record is allocated on the stack to hold: –return address (where to return after execution) –parameters –local variables (stuff declared in the method) When a method returns, the activation record is popped Main: ObjA a = new ObjA(); ObjB b = new ObjB(); a.do(5, b) public class ObjA { int x = 100; public void do (int y, ObjB myB) { int loc = 6; int t = myB.doMore(loc);... } public class ObjB { int z = 30; public int doMore(int i) { z = z + i; return z; }

Consider Factorial Example class FacTest { static public void main (String [] args) { int f = factorial(3); // * System.out.println(“Factorial of 3 is “ + f); } static public int factorial (int n) { int c = n – 1; int r; if (c > 0) { r = n * factorial(c); // ** } else { r = 1; } return r; }