Chapter 11 Classes Continued

Size: px
Start display at page:

Download "Chapter 11 Classes Continued"

Transcription

1 Chapter 11 Classes Continued The real power of object-oriented programming comes from its capacity to reduce code and to distribute responsibilities for such things as error handling in a software system. Important concepts of this chapter o Static Variables and Methods: When information needs to be shared among all instances of a class, that information can be represented in terms of static variables and it can be accessed by means of static method. o Interfaces: A Java interface specifies the set of methods available to clients of a class. An interface provides a way of requiring a class to implement a set of methods and a way of informing clients about services regardless of implementation details. Interfaces thus provide the glue that holds a set of cooperating classes together. o Inheritance: Java organizes classes in a hierarchy. Classes inherit the instance variables and methods of the classes above them in the hierarchy. A class can extend its inherited characteristics by adding instance variables and methods and by overriding inherited methods. Thus inheritance provides a mechanism for reusing code and can greatly reduce the effort required to implement a new class. o Abstract Classes: Some classes in a hierarchy must never be instantiated. They are called abstract classes. Their sole purpose is to define features and behavior common to their subclasses. o Polymorphism: Methods in different classes with a similar function are usually given the same name. This is called polymorphism. Polymorphism makes classes easier to use because programmers need to memorize fewer method names. In a well-designed class hierarchy, polymorphism is employed as much as possible. A good example of a polymorphic message is tostring. Every object, no matter which class it belongs to, understands the tostring message and responds by returning a string that describes the object. o Preconditions and Postconditions: Clients need to know how to use a method correctly and what results to expect if it is so used. Preconditions specify the correct use of a method and postconditions describe what will result if the preconditions are satisfied.

2 o Exceptions for Error Handling: When a method's preconditions are violated, a foolproof way to catch the errors is to throw exceptions, thereby halting program execution at the point of the errors. o Reference Types: The identity of an object and the fact that there can be multiple references to the same object are issues that arise when comparing two objects for equality and when copying an object. There are also subtle rules to master when manipulating objects of different but related types in a hierarchy. Instance Variables: belongs to object and storage is allocated when object created. Each object has own set of instance variables, activated when a message is sent to object. Instance Method: is activated when a message is sent to an object. Class Variable: belongs to a class. Its storage is allocated at program start-up and is independent of the number of instances created. Class Method: is activated when a message is sent to the class rather than to an object The modifier static is used to designate class variables and methods. We use a static variable in any situation in which all instances share a common data value. We then use static methods to provide public access to these data. By using the modifier final in conjunction with static, we create a class constant. Value is assigned when variable is declared and cannot change. Rules for using static Variables 1) Class methods can reference only static variables, and never the instance variables. 2) Instance methods can reference static and instance variables. Rather than decompose a problem into a system of cooperating static methods, it is much better to decompose it into a system of cooperating classes. With the later approach, static main usually is limited to the small but essential role of starting everything off.

3 In Turtle Graphics a pen is initially: o In the center of a graphics window (0, 0) o In the down position o Pointing north To use Turtle Graphics remember to: o import TurtleGraphics.StandardPen; o Standard pen = new StandardPen(); // Or other type pen Interface is used in two ways: 1) Part of a software system that interacts with human users 2) It is a list of a class's public methods. (We will talk about this one) A class's interface provides the information needed to use a class without revealing anything about its implementation. Types of Pens (all have same general behavior and respond to same messages) o StandardPen o WigglePen o RainbowPen

4 // Pen.java: The behavior common to all types of pens import java.awt.color public interface Pen { public String } down(); drawstring(string text); home(); move(double distance); move(double x, double y); setcolor(color color); setdirection(double direction); setwidth(int width); tostring(); turn(double degrees); up(); Interface only contains the signatures of the methods followed by semicolon. It provides programmers the information need to use pens of any type correctly. Interface is not a class; however, when a class is defined there is a mechanism, to specify that the class conforms to the interface. ** Look at code in DifferentPens that puts drawing of a square in a method. Using an interface name has two benefits: 1. Methods that use interface types are more general, in that they work with any classes that implement the interface. 2. It s easier to maintain a program that uses interface types. If you want to modify the program to use a different type of pen, for example, you only have to change the code that instantiates the pen. The code that manipulates the pen does not have to change at all. See page 394 and interface Shape public class Circle implements Shape { } public class Rect implements Shape { }

5 The key feature is the phrase implements Shape. The presence of this phrase implies that: Both classes implement all the methods listed in the Shape interface. A variable declared as Shape can be associated with an object of either class. Look at code page Final Observations on Interface An interface contains only methods, never variables. The methods in an interface are usually public. If more than one class implements an interface, its methods are polymorphic. A class can implement methods in addition to those listed in the interface, as we will illustrate soon. A class can implement more than one interface, a feature that we are not going to explore. Interfaces can be organized in an inheritance hierarchy, another feature we are not going to explore. Code reuse through inheritance All classes part of immense hierarchy, with class Object at the root. Each class inherits the characteristics (variables and methods) of the classes above it in the hierarchy. A class can add new variables to these inherited characteristics as needed. It also can add new methods and/or modifies inherited methods. Root top position in an upside down tree (Object class) Subclasses are below the Object class (subclasses extend Object) Superclass class immediately above another A class can have many subclasses, and all classes, except Object have exactly one superclass. Descendants of a class consists of its subclasses, plus their subclasses, and so on. See Wheel example. Wheel v1 = new Wheel(); Shape v2 = new Wheel(); v1.setspokes(6); v2.setspokes(6); ******error*****

6 ((Wheel)v2).setSpokes(6); ***cast to wheel before use method*** Arrays of Objects Shapes[] shapes = new Shape[10]; shapes[0] = new Rect(20,20,40,40); shapes[1] = new Circle(100,100,20); shapes[2] = new Wheel(200,200,20,6); Pen pen = new StandardPen(); for (int i = 0; i < 3; i++) shapes[i].draw(pen); setspokes(n)???????? for(int i = 0; i < shapes.length; i++) if (shapes[i] instanceof Wheel) ((Wheel)shapes[i]).setSpokes(5); Important facts about objects in arrays: 1. When an element type of an array is a reference type or interface, objects of those types or any subtype (subclass or implementing class) can be directly inserted into the array. 2. After accessing an object in an array, care must be taken to send it the appropriate messages or to cast it down to a type that can receive the appropriate messages Inheritance and Abstract Classes The Circle and Rect classes duplicate code. Inheritance provides ways to reduce duplication. We define a new class that is a superclass of Circle and Rect and contains all the variables and methods common to both. We will never instantiate this class, so we will make it an abstract class, that is, a class that cannot be instantiated. The classes that extend this class and that are instantiated are called concrete classes. Call the class AbstractShape and have it implement the Shape interface. Then, the subclasses of Circle and Rect no longer need to implement Shape explicitly. Since AbstractShape implements Shape, it must include all the Shape methods, even those that are completely different in the subclasses and share no code (like area). Methods in AbstractShape such as area for which we cannot write any code are

7 called abstract methods, and we indicate that fact by including the word abstract in their headers. See code pages A final method is a method that cannot be overridden by a subclass. Some Observations about Interfaces and Inheritance A Java interface has a name and consists of a list of method headers. One or more classes can implement the same interface. If a variable is declared to be of an interface type, then it can be associated with an object from any class that implements the interface. If a class implements an interface, then all its subclasses do so implicitly. A subclass inherits all the characteristics of its superclass. To this basis, the subclass can add new variables and methods or modify inherited methods. Characteristics common to several classes can be collected in a common abstract superclass that is never instantiated.

8 An abstract class can contain headers for abstract methods that are implemented in the subclasses. A class's constructors and methods can utilize constructors and methods in the superclass. Inheritance reduces repetition and promotes the reuse of code. Interfaces and inheritance promote the use of polymorphism. There are four ways in which methods in a subclass can be related to methods in a superclass: 1. Implementation of an abstract method: As we have seen, each subclass is forced to implement the abstract methods specified in its superclass. Abstract methods are thus a means of requiring certain behavior in all subclasses. 2. Extension: There are two kinds of extension: a. The subclass method does not exist in the superclass. b. The subclass method invokes the same method in the superclass and also extends the superclass's behavior with its own operations. 3. Overriding: In the case of overriding, the subclass method does not invoke the superclass method. Instead, the subclass method is intended as a complete replacement of the superclass method. 4. Finality: The method in the superclass is complete and cannot be modified by the subclasses. We declare such a method to be final. Page 413 (Working without interfaces) So should you or shouldn't you use interfaces? This is not really a question of vital importance in an introductory programming class where all the programs are relatively short and simple: however, the prevailing wisdom suggests that we use hierarchies of interfaces to organize behavior and hierarchies of classes to maximize code reuse. Justifying this advice is beyond this book's scope.

9 Relationships among Classes 1. An object of one class can send a message to an object of another class. For example, a Circle object sends a message to a StandardPen object to draw a shape. In this case, the sender object s class depends on the receiver object s class, and their relationship is called dependency. 2. An object of one class can contain objects of another class as structural components. For example, the TestScoresModel object contains Student objects. The relationship between a container class and the classes of the objects it contains is called aggregation or the has-a relationship. 3. An object s class can be a subclass of a more general class. For example, the Wheel class is a subclass of Circle, which in turn is a subclass of AbstractShape. These classes are related by inheritance, or the is-a relationship. UML diagrams

10 Acceptable Classes for parameters & return types: In any situation in which an object of a superclass is expected, it is always acceptable to substitute an object of a subclass, but never a superclass AbstractShape A; Circle B; Rect C; A = new Circle(); B = new AbstractShape(); C = new AbstractShape(); A = new Rect(); B = new Rect(); C = new Circle(); A = new Wheel(); B = new Wheel(); C = new Wheel(); Wheel D; D = new AbstractShape(); D = new Circle(); D = new Rect(); Object (references) can be passes to/from methods Changes made to objects in methods persist after method. An object returned by method is usually created in method. It continues to exist after method stops executing. Preconditions describe the expected values of a parameters and instance variable that the method is about to use. Postconditions describe the return value and any changes made to instance variables. Preconditions and Postconditions are written as comments placed immediately before a method s header. /* * Precondition: 1 <= i< =number of scores * Precondition: 0 <= score <= 100 * Postcondition: test score at position i is set to score * Returns: true if the preconditions are satisfied or false otherwise */ public boolean setscore(int i, int score) { if (i < 1 i > tests.length score < 0 score > 100) return false; tests[i 1] = score; return true; }

11 Commonly used exceptions classes in package java.lang Exception RuntimeException ArithmeticException IllegalArgumentException IllegalStateException IndexOutOfBoundsException StringIndexOutOfBoundsException ArrayIndexOutOfBoundsException NullPointerException UnsupportedOperationException throw new <exception class>(<a string>); Could use to enforce preconditions. if (number < 0) throw new RuntimeException( Number should be nonnegative); ***See student example Could use try catch so exceptions do not halt execution of program (See page ) Show documentation using Bluej @throws 11.12: Reference types, Equality, and Object Identity Alias (aliasing) a situation in which two or more names in a program can refer to the same location. This happens when a programmer assigns one object variable to another. Comparing Objects for Equality 1. Use equality operator == 2. Use instance method equals (in object class defined and uses == by default. May be overridden in other classes like tostring)

12 String str = reader.nextline( ); System.out.println(str == "Java"); System.out.println(str.equals("Java")); The objects referenced by the variable str and the literal "Java" are two different string objects in memory, even though the characters they contain might be the same. The first string object was created in the keyboard reader during user input; the second string object was created internally within the program. The operator == compares the references to the objects, not the contents of the objects. Thus, if the two references do not point to the same object in memory, == returns false. Because the two strings in our example are not the same object in memory, == returns false. The method equals returns true, even when two strings are not the same object in memory, if their characters happen to be the same. If at least one pair of characters fails to match, the method equals returns false. A corollary of these facts is that the operator!= can return true for two strings, even though the method equals returns true. To summarize, == tests for object identity, whereas equals tests for structural similarity as defined by the implementing class. Write own equal class for other objects do not use ==. //Compare two students for equality public Boolean equals (Object other) { if (this == other) //test for identity return true; if (!(Other instanceof Student)) // test for Student return false; Student s = (Student)other; //cast to student Return name.equals(s.getname( )); //compare the names }

13 Copying Objects Student s1, s2; s1 = new Student("Mary", 100, 80, 75); s2 = s1; s1 and s2 refer to the same object When clients of a class might copy objects, there is a standard way of providing a method to do this. The class implements the Java interface Cloneable. This interface authorizes the method clone, which is defined in the Object class, to construct a copy of the object. Student s1, s2; s1 = new Student("Mary", 100, 80, 75); s2 = s1.clone( );

Chapter 10 Classes Continued. Fundamentals of Java

Chapter 10 Classes Continued. Fundamentals of Java Chapter 10 Classes Continued Objectives Know when it is appropriate to include class (static) variables and methods in a class. Understand the role of Java interfaces in a software system and define an

More information

APCS Java Lesson 10: Classes Continued Modifications by Mr. Dave Clausen Updated for Java 1.5

APCS Java Lesson 10: Classes Continued Modifications by Mr. Dave Clausen Updated for Java 1.5 APCS Java Lesson 10: Classes Continued Modifications by Mr. Dave Clausen Updated for Java 1.5 1 Lesson 10: Classes Continued Objectives: Know when it is appropriate to include class (static) variables

More information

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED EXERCISE 11.1 1. static public final int DEFAULT_NUM_SCORES = 3; 2. Java allocates a separate set of memory cells in each instance

More information

OBJECT ORİENTATİON ENCAPSULATİON

OBJECT ORİENTATİON ENCAPSULATİON OBJECT ORİENTATİON Software development can be seen as a modeling activity. The first step in the software development is the modeling of the problem we are trying to solve and building the conceptual

More information

Inheritance, Polymorphism, and Interfaces

Inheritance, Polymorphism, and Interfaces Inheritance, Polymorphism, and Interfaces Chapter 8 Inheritance Basics (ch.8 idea) Inheritance allows programmer to define a general superclass with certain properties (methods, fields/member variables)

More information

Object Oriented Programming. Java-Lecture 11 Polymorphism

Object Oriented Programming. Java-Lecture 11 Polymorphism Object Oriented Programming Java-Lecture 11 Polymorphism Abstract Classes and Methods There will be a situation where you want to develop a design of a class which is common to many classes. Abstract class

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 05: Inheritance and Interfaces MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Inheritance and Interfaces 2 Introduction Inheritance and Class Hierarchy Polymorphism Abstract

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation

More information

CS-202 Introduction to Object Oriented Programming

CS-202 Introduction to Object Oriented Programming CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture III Inheritance and Polymorphism Introduction to Inheritance Introduction

More information

Polymorphism and Interfaces. CGS 3416 Spring 2018

Polymorphism and Interfaces. CGS 3416 Spring 2018 Polymorphism and Interfaces CGS 3416 Spring 2018 Polymorphism and Dynamic Binding If a piece of code is designed to work with an object of type X, it will also work with an object of a class type that

More information

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L Inheritance Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 9.4 1 Inheritance Inheritance allows a software developer to derive

More information

Inheritance and Interfaces

Inheritance and Interfaces Inheritance and Interfaces Object Orientated Programming in Java Benjamin Kenwright Outline Review What is Inheritance? Why we need Inheritance? Syntax, Formatting,.. What is an Interface? Today s Practical

More information

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods. Inheritance Inheritance is the act of deriving a new class from an existing one. Inheritance allows us to extend the functionality of the object. The new class automatically contains some or all methods

More information

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

Java Object Oriented Design. CSC207 Fall 2014

Java Object Oriented Design. CSC207 Fall 2014 Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code

More information

8. Polymorphism and Inheritance

8. Polymorphism and Inheritance 8. Polymorphism and Inheritance Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich http://seal.ifi.uzh.ch/info1 Objectives Describe polymorphism and inheritance in general Define interfaces

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation

More information

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2) Software Paradigms (Lesson 3) Object-Oriented Paradigm (2) Table of Contents 1 Reusing Classes... 2 1.1 Composition... 2 1.2 Inheritance... 4 1.2.1 Extending Classes... 5 1.2.2 Method Overriding... 7 1.2.3

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Object Oriented Programming Designed and Presented by Dr. Ayman Elshenawy Elsefy Dept. of Systems & Computer Eng.. Al-Azhar University Website: eaymanelshenawy.wordpress.com Email : eaymanelshenawy@azhar.edu.eg

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 05: Inheritance and Interfaces MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Inheritance and Interfaces 2 Introduction Inheritance and Class Hierarchy Polymorphism Abstract Classes

More information

First IS-A Relationship: Inheritance

First IS-A Relationship: Inheritance First IS-A Relationship: Inheritance The relationships among Java classes form class hierarchy. We can define new classes by inheriting commonly used states and behaviors from predefined classes. A class

More information

Object Oriented Features. Inheritance. Inheritance. CS257 Computer Science I Kevin Sahr, PhD. Lecture 10: Inheritance

Object Oriented Features. Inheritance. Inheritance. CS257 Computer Science I Kevin Sahr, PhD. Lecture 10: Inheritance CS257 Computer Science I Kevin Sahr, PhD Lecture 10: Inheritance 1 Object Oriented Features For a programming language to be called object oriented it should support the following features: 1. objects:

More information

More Relationships Between Classes

More Relationships Between Classes More Relationships Between Classes Inheritance: passing down states and behaviors from the parents to their children Interfaces: grouping the methods, which belongs to some classes, as an interface to

More information

Polymorphism and Inheritance

Polymorphism and Inheritance Walter Savitch Frank M. Carrano Polymorphism and Inheritance Chapter 8 Objectives Describe polymorphism and inheritance in general Define interfaces to specify methods Describe dynamic binding Define and

More information

Polymorphism. return a.doublevalue() + b.doublevalue();

Polymorphism. return a.doublevalue() + b.doublevalue(); Outline Class hierarchy and inheritance Method overriding or overloading, polymorphism Abstract classes Casting and instanceof/getclass Class Object Exception class hierarchy Some Reminders Interfaces

More information

What is Inheritance?

What is Inheritance? Inheritance 1 Agenda What is and Why Inheritance? How to derive a sub-class? Object class Constructor calling chain super keyword Overriding methods (most important) Hiding methods Hiding fields Type casting

More information

More on Objects in JAVA TM

More on Objects in JAVA TM More on Objects in JAVA TM Inheritance : Definition: A subclass is a class that extends another class. A subclass inherits state and behavior from all of its ancestors. The term superclass refers to a

More information

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

Casting -Allows a narrowing assignment by asking the Java compiler to "trust us"

Casting -Allows a narrowing assignment by asking the Java compiler to trust us Primitives Integral types: int, short, long, char, byte Floating point types: double, float Boolean types: boolean -passed by value (copied when returned or passed as actual parameters) Arithmetic Operators:

More information

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner. HAS-A Relationship Association is a relationship where all objects have their own lifecycle and there is no owner. For example, teacher student Aggregation is a specialized form of association where all

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

CSE1720. General Info Continuation of Chapter 9 Read Chapter 10 for next week. Second level Third level Fourth level Fifth level

CSE1720. General Info Continuation of Chapter 9 Read Chapter 10 for next week. Second level Third level Fourth level Fifth level CSE1720 Click to edit Master Week text 08, styles Lecture 13 Second level Third level Fourth level Fifth level Winter 2014! Thursday, Feb 27, 2014 1 General Info Continuation of Chapter 9 Read Chapter

More information

This week. Tools we will use in making our Data Structure classes: Generic Types Inheritance Abstract Classes and Interfaces

This week. Tools we will use in making our Data Structure classes: Generic Types Inheritance Abstract Classes and Interfaces This week Tools we will use in making our Data Structure classes: Generic Types Inheritance Abstract Classes and Interfaces This is a lot of material but we'll be working with these tools the whole semester

More information

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

More About Objects. Zheng-Liang Lu Java Programming 255 / 282 More About Objects Inheritance: passing down states and behaviors from the parents to their children. Interfaces: requiring objects for the demanding methods which are exposed to the outside world. Polymorphism

More information

Inheritance. Inheritance

Inheritance. Inheritance 1 2 1 is a mechanism for enhancing existing classes. It allows to extend the description of an existing class by adding new attributes and new methods. For example: class ColoredRectangle extends Rectangle

More information

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner. HAS-A Relationship Association is a relationship where all objects have their own lifecycle and there is no owner. For example, teacher student Aggregation is a specialized form of association where all

More information

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2 CITS2200 Data Structures and Algorithms Topic 2 Java Primer Review of Java basics Primitive vs Reference Types Classes and Objects Class Hierarchies Interfaces Exceptions Reading: Lambert and Osborne,

More information

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014 Lesson 10A OOP Fundamentals By John B. Owen All rights reserved 2011, revised 2014 Table of Contents Objectives Definition Pointers vs containers Object vs primitives Constructors Methods Object class

More information

Declarations and Access Control SCJP tips

Declarations and Access Control  SCJP tips Declarations and Access Control www.techfaq360.com SCJP tips Write code that declares, constructs, and initializes arrays of any base type using any of the permitted forms both for declaration and for

More information

Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal

Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Define and discuss abstract classes Define and discuss abstract methods Introduce polymorphism Much of the information

More information

EXCEPTION HANDLING. Summer 2018

EXCEPTION HANDLING. Summer 2018 EXCEPTION HANDLING Summer 2018 EXCEPTIONS An exception is an object that represents an error or exceptional event that has occurred. These events are usually errors that occur because the run-time environment

More information

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

More information

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism.

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism. Outline Inheritance Class Extension Overriding Methods Inheritance and Constructors Polymorphism Abstract Classes Interfaces 1 OOP Principles Encapsulation Methods and data are combined in classes Not

More information

Chapter 14 Abstract Classes and Interfaces

Chapter 14 Abstract Classes and Interfaces Chapter 14 Abstract Classes and Interfaces 1 What is abstract class? Abstract class is just like other class, but it marks with abstract keyword. In abstract class, methods that we want to be overridden

More information

Full file at Chapter 2 - Inheritance and Exception Handling

Full file at   Chapter 2 - Inheritance and Exception Handling Chapter 2 - Inheritance and Exception Handling TRUE/FALSE 1. The superclass inherits all its properties from the subclass. ANS: F PTS: 1 REF: 76 2. Private members of a superclass can be accessed by a

More information

Inheritance and object compatibility

Inheritance and object compatibility Inheritance and object compatibility Object type compatibility An instance of a subclass can be used instead of an instance of the superclass, but not the other way around Examples: reference/pointer can

More information

Prelim 1 SOLUTION. CS 2110, September 29, 2016, 7:30 PM Total Question Name Loop invariants. Recursion OO Short answer

Prelim 1 SOLUTION. CS 2110, September 29, 2016, 7:30 PM Total Question Name Loop invariants. Recursion OO Short answer Prelim 1 SOLUTION CS 2110, September 29, 2016, 7:30 PM 0 1 2 3 4 5 Total Question Name Loop invariants Recursion OO Short answer Exception handling Max 1 15 15 25 34 10 100 Score Grader 0. Name (1 point)

More information

More on Exception Handling

More on Exception Handling Chapter 18 More on Exception Handling Lecture slides for: Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2

More information

CH. 2 OBJECT-ORIENTED PROGRAMMING

CH. 2 OBJECT-ORIENTED PROGRAMMING CH. 2 OBJECT-ORIENTED PROGRAMMING ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER (WILEY 2016) OBJECT-ORIENTED

More information

More on Exception Handling

More on Exception Handling Chapter 18 More on Exception Handling Lecture slides for: Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2

More information

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes. a and Interfaces Class Shape Hierarchy Consider the following class hierarchy Shape Circle Square Problem AND Requirements Suppose that in order to exploit polymorphism, we specify that 2-D objects must

More information

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A. HAS-A Relationship Association is a weak relationship where all objects have their own lifetime and there is no ownership. For example, teacher student; doctor patient. If A uses B, then it is an aggregation,

More information

Inheritance -- Introduction

Inheritance -- Introduction Inheritance -- Introduction Another fundamental object-oriented technique is called inheritance, which, when used correctly, supports reuse and enhances software designs Chapter 8 focuses on: the concept

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 20, 2014 Abstract

More information

Chapter 5 Object-Oriented Programming

Chapter 5 Object-Oriented Programming Chapter 5 Object-Oriented Programming Develop code that implements tight encapsulation, loose coupling, and high cohesion Develop code that demonstrates the use of polymorphism Develop code that declares

More information

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance?

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance? CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 5: Inheritance & Polymorphism Lecture Contents 2 What is Inheritance? Super-class & sub class Protected members Creating subclasses

More information

Inheritance (Outsource: )

Inheritance (Outsource: ) (Outsource: 9-12 9-14) is a way to form new classes using classes that have already been defined. The new classes, known as derived classes, inherit attributes and behavior of the pre-existing classes,

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 21, 2013 Abstract

More information

Language Features. 1. The primitive types int, double, and boolean are part of the AP

Language Features. 1. The primitive types int, double, and boolean are part of the AP Language Features 1. The primitive types int, double, and boolean are part of the AP short, long, byte, char, and float are not in the subset. In particular, students need not be aware that strings are

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

Inheritance. Transitivity

Inheritance. Transitivity Inheritance Classes can be organized in a hierarchical structure based on the concept of inheritance Inheritance The property that instances of a sub-class can access both data and behavior associated

More information

CS 520 Theory and Practice of Software Engineering Fall 2018

CS 520 Theory and Practice of Software Engineering Fall 2018 Today CS 520 Theory and Practice of Software Engineering Fall 2018 Object Oriented (OO) Design Principles September 13, 2018 Code review and (re)design of an MVC application (and encapsulation) Polymorphism

More information

Subclasses, Superclasses, and Inheritance

Subclasses, Superclasses, and Inheritance Subclasses, Superclasses, and Inheritance To recap what you've seen before, classes can be derived from other classes. The derived class (the class that is derived from another class) is called a subclass.

More information

Class Hierarchy and Interfaces. David Greenstein Monta Vista High School

Class Hierarchy and Interfaces. David Greenstein Monta Vista High School Class Hierarchy and Interfaces David Greenstein Monta Vista High School Inheritance Inheritance represents the IS-A relationship between objects. an object of a subclass IS-A(n) object of the superclass

More information

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 5: Inheritance & Polymorphism Lecture Contents 2 What is Inheritance? Super-class & sub class Protected members Creating subclasses

More information

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages Preliminaries II 1 Agenda Objects and classes Encapsulation and information hiding Documentation Packages Inheritance Polymorphism Implementation of inheritance in Java Abstract classes Interfaces Generics

More information

CS 11 java track: lecture 3

CS 11 java track: lecture 3 CS 11 java track: lecture 3 This week: documentation (javadoc) exception handling more on object-oriented programming (OOP) inheritance and polymorphism abstract classes and interfaces graphical user interfaces

More information

Inheritance. SOTE notebook. November 06, n Unidirectional association. Inheritance ("extends") Use relationship

Inheritance. SOTE notebook. November 06, n Unidirectional association. Inheritance (extends) Use relationship Inheritance 1..n Unidirectional association Inheritance ("extends") Use relationship Implementation ("implements") What is inherited public, protected methods public, proteced attributes What is not inherited

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Inheritance and Polymorphism Inheritance (Continued) Polymorphism Polymorphism by inheritance Polymorphism by interfaces Reading for this lecture: L&L 10.1 10.3 1 Interface Hierarchies Inheritance can

More information

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming Overview of OOP Object Oriented Programming is a programming method that combines: a) Data b) Instructions for processing that data into a self-sufficient object that can be used within a program or in

More information

Classes and Inheritance Extending Classes, Chapter 5.2

Classes and Inheritance Extending Classes, Chapter 5.2 Classes and Inheritance Extending Classes, Chapter 5.2 Dr. Yvon Feaster Inheritance Inheritance defines a relationship among classes. Key words often associated with inheritance are extend and implements.

More information

Object Oriented Java

Object Oriented Java Object Oriented Java I. Object based programming II. Object oriented programing M. Carmen Fernández Panadero Raquel M. Crespo García Contents Polymorphism Dynamic binding Casting.

More information

Java How to Program, 8/e

Java How to Program, 8/e Java How to Program, 8/e Polymorphism Enables you to program in the general rather than program in the specific. Polymorphism enables you to write programs that process objects that share the same superclass

More information

Inheritance Chapter 8. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Inheritance Chapter 8. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Inheritance Chapter 8 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 2 Scope Class Inheritance: Deriving classes Method overriding Class hierarchies Abstract classes Visibility and inheritance

More information

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Marenglen Biba Exception handling Exception an indication of a problem that occurs during a program s execution. The name exception implies that the problem occurs infrequently. With exception

More information

Inheritance. The Java Platform Class Hierarchy

Inheritance. The Java Platform Class Hierarchy Inheritance In the preceding lessons, you have seen inheritance mentioned several times. In the Java language, classes can be derived from other classes, thereby inheriting fields and methods from those

More information

COMP1008 An overview of Polymorphism, Types, Interfaces and Generics

COMP1008 An overview of Polymorphism, Types, Interfaces and Generics COMP1008 An overview of Polymorphism, Types, Interfaces and Generics Being Object-Oriented Exploiting the combination of: objects classes encapsulation inheritance dynamic binding polymorphism pluggability

More information

Definition of DJ (Diminished Java)

Definition of DJ (Diminished Java) Definition of DJ (Diminished Java) version 0.5 Jay Ligatti 1 Introduction DJ is a small programming language similar to Java. DJ has been designed to try to satisfy two opposing goals: 1. DJ is a complete

More information

Type Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004

Type Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004 Type Hierarchy Comp-303 : Programming Techniques Lecture 9 Alexandre Denault Computer Science McGill University Winter 2004 February 16, 2004 Lecture 9 Comp 303 : Programming Techniques Page 1 Last lecture...

More information

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,

More information

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II 1 CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 8(b): Abstract classes & Polymorphism Lecture Contents 2 Abstract base classes Concrete classes Polymorphic processing Dr. Amal Khalifa,

More information

CS 251 Intermediate Programming Inheritance

CS 251 Intermediate Programming Inheritance CS 251 Intermediate Programming Inheritance Brooke Chenoweth University of New Mexico Spring 2018 Inheritance We don t inherit the earth from our parents, We only borrow it from our children. What is inheritance?

More information

Inheritance & Polymorphism

Inheritance & Polymorphism E H U N I V E R S I T Y T O H F R G E D I N B U Murray Cole Classifying Things 1 Hierarchies help us to classify things and understand their similarities and differences Some aspects are common to everything

More information

Lecture 4: Extending Classes. Concept

Lecture 4: Extending Classes. Concept Lecture 4: Extending Classes Concept Inheritance: you can create new classes that are built on existing classes. Through the way of inheritance, you can reuse the existing class s methods and fields, and

More information

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Marenglen Biba (C) 2010 Pearson Education, Inc. All Inheritance A form of software reuse in which a new class is created by absorbing an existing class s members and enriching them with

More information

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017 Inheritance Lecture 11 COP 3252 Summer 2017 May 25, 2017 Subclasses and Superclasses Inheritance is a technique that allows one class to be derived from another. A derived class inherits all of the data

More information

Self-review Questions

Self-review Questions 7Class Relationships 106 Chapter 7: Class Relationships Self-review Questions 7.1 How is association between classes implemented? An association between two classes is realized as a link between instance

More information

Polymorphism: Inheritance Interfaces

Polymorphism: Inheritance Interfaces Polymorphism: Inheritance Interfaces 256 Recap Finish Deck class methods Questions about assignments? Review Player class for HW9 (starter zip posted) Lessons Learned: Arrays of objects require multiple

More information

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are built on top of that. CMSC131 Inheritance Object When we talked about Object, I mentioned that all Java classes are "built" on top of that. This came up when talking about the Java standard equals operator: boolean equals(object

More information

A Java Execution Simulator

A Java Execution Simulator A Java Execution Simulator Steven Robbins Department of Computer Science University of Texas at San Antonio srobbins@cs.utsa.edu ABSTRACT This paper describes JES, a Java Execution Simulator that allows

More information

[ L5P1] Object-Oriented Programming: Advanced Concepts

[ L5P1] Object-Oriented Programming: Advanced Concepts [ L5P1] Object-Oriented Programming: Advanced Concepts Polymorphism Polymorphism is an important and useful concept in the object-oriented paradigm. Take the example of writing a payroll application for

More information

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting Lecture 36: Cloning Last time: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting Today: 1. Project #7 assigned 2. equals reconsidered 3. Copying and cloning 4. Composition 11/27/2006

More information

Index. Index. More information. block statements 66 y 107 Boolean 107 break 55, 68 built-in types 107

Index. Index. More information. block statements 66 y 107 Boolean 107 break 55, 68 built-in types 107 A abbreviations 17 abstract class 105 abstract data types 105 abstract method 105 abstract types 105 abstraction 92, 105 access level 37 package 114 private 115 protected 115 public 115 accessors 24, 105

More information

More On inheritance. What you can do in subclass regarding methods:

More On inheritance. What you can do in subclass regarding methods: More On inheritance What you can do in subclass regarding methods: The inherited methods can be used directly as they are. You can write a new static method in the subclass that has the same signature

More information

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U C A N A D I A N I N T E R N A T I O N A L S C H O O L O F H O N G K O N G INHERITANCE & POLYMORPHISM P2 LESSON 12 P2 LESSON 12.1 INTRODUCTION inheritance: OOP allows a programmer to define new classes

More information

Inheritance (continued) Inheritance

Inheritance (continued) Inheritance Objectives Chapter 11 Inheritance and Polymorphism Learn about inheritance Learn about subclasses and superclasses Explore how to override the methods of a superclass Examine how constructors of superclasses

More information

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University CS5000: Foundations of Programming Mingon Kang, PhD Computer Science, Kennesaw State University Inheritance Three main programming mechanisms that constitute object-oriented programming (OOP) Encapsulation

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions

More information

Classes, interfaces, & documentation. Review of basic building blocks

Classes, interfaces, & documentation. Review of basic building blocks Classes, interfaces, & documentation Review of basic building blocks Objects Data structures literally, storage containers for data constitute object knowledge or state Operations an object can perform

More information