1 Abstract Classes & Inheritance Hierarchies. 2 Abstract classes & methods Keyword abstract applied to a class guarantees that subclass must be constructed.

Slides:



Advertisements
Similar presentations
Final and Abstract Classes
Advertisements

1 Chapter 6: Extending classes and Inheritance. 2 Basics of Inheritance One of the basic objectives of Inheritance is code reuse If you want to extend.
CS 211 Inheritance AAA.
Inheritance Java permits you to use your user defined classes to create programs using inheritance.
C8: Understanding Inheritance. Intuitive description Intuitive: FLORISTS are SHOPKEEPERS, inheriting various shopkeeper behaviors Tension in OOP languages:
Chapter 10: Introduction to Inheritance
Interface & Abstract Class. Interface Definition All method in an interface are abstract methods. Methods are declared without the implementation part.
Object-Oriented PHP (1)
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.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
CS 2511 Fall  Abstraction Abstract class Interfaces  Encapsulation Access Specifiers Data Hiding  Inheritance  Polymorphism.
Chapter 10 Classes Continued
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
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.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
An Object-Oriented Approach to Programming Logic and Design
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Recap (önemli noktaları yinelemek) from last week Paradigm Kay’s Description Intro to Objects Messages / Interconnections Information Hiding Classes Inheritance.
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.
CSE 501N Fall ‘09 14: Inheritance 20 October 2009 Nick Leidenfrost.
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 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.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Inheritance and Access Control CS 162 (Summer 2009)
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.
OOPs Object oriented programming. Abstract data types  Representationof type and operations in a single unit  Available for other units to create variables.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
Final Review. From ArrayLists to Arrays The ArrayList : used to organize a list of objects –It is a class in the Java API –the ArrayList class uses an.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Coming up: Inheritance
JAVA Programming (Session 4) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Java Programming, Second Edition Chapter Twelve Advanced Inheritance Concepts.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Classes, Interfaces and Packages
Programming & Debugging. Key Programming Issues Modularity Modifiability Ease of Use Fail-safe programming Style Debugging.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Inheritance a subclass extends the functionality of a superclass a subclass inherits all the functionality of a superclass don't reinvent the wheel – "stand.
OOP: Encapsulation &Abstraction
Inheritance and Polymorphism
Inheritance and Abstract Classes
Week 4 Object-Oriented Programming (1): Inheritance
Java Programming Language
MSIS 670 Object-Oriented Software Engineering
Advanced Programming Behnam Hatami Fall 2017.
Advanced Java Programming
Object-Oriented Programming: Inheritance and Polymorphism
Chapter 14 Abstract Classes and Interfaces
CS 112 Programming 2 Lecture 02 Abstract Classes & Interfaces (2)
Final and Abstract Classes
Presentation transcript:

1 Abstract Classes & Inheritance Hierarchies

2 Abstract classes & methods Keyword abstract applied to a class guarantees that subclass must be constructed Individual methods in an abstract class can be declared abstract; such methods must be overridden by child classes Abstract classes almost always contain abstract methods, but not all methods have to be abstract

3 Abstract classes & methods Abstract methods are like interface methods: specified but undefined Abstract classes are used to factor out common behavior from sets of related (sub)classes Abstract classes cannot be instantiated; but, as with interfaces, can declare variables of abstract class type

4 Abstract classes Abstract classes are created strictly as superclasses Can have instance fields and methods Can tag any class as abstract; means can’t create objects from this class, but can inherit from it

5 Abstract classes Vs. interfaces Advantage of abstract class is ability to define some behavior as well as specify it; more can be inherited from an abstract class than from an interface Disadvantage is lack of multiple inheritance; can only inherit from one class, but can implement as many interfaces as desired

6 Abstract classes Vs. interfaces Abstract classes can have fields Interface types can only have constants ( public static final ) Abstract classes can define methods Interface types can only declare methods

7 Abstract classes & interfaces Good idea to supply both an interface type and a class that implements some of its methods with convenient defaults; gives best of both worlds Java library has many examples of such pairs

8 Modifiers and Inheritance Public data field or method can be accessed outside its class definition; a public class can be accessed outside its package Protected data field or method can be accessed within its class, within other classes in its package, or within subclasses Private data field or method can be accessed only within its class

9 Modifiers and Inheritance Static fields are shared by all instances of a class & can be invoked even is no class instance has been created; static methods cannot be overridden Abstract classes cannot be instantiated, and can only be used as parent classes

10 Modifiers and Inheritance Modifier final is opposite of abstract: –when applied to a class, means the class cannot be subclassed –when applied to a method, means method cannot be overridden –when applied to a variable, the variable becomes a constant

11 Benefits of Inheritance Software reusability –code sharing –reusable components Increased reliability: code that is executed frequently tends to have fewer bugs Interface consistency Information hiding

12 Costs of Inheritance Execution speed - inherited methods often slower than code written for specific purpose Program size Message-passing overhead Program complexity

13 Inheritance Vs. Composition Both are techniques for software reuse Inheritance is appropriate in a situation when one object is a specialized type of another object -- e.g. a professor is a teacher Composition is appropriate when an object is made up of other objects -- e.g. a blender has a motor, a set of controls, and a container to hold the contents

14 Hierarchy of Swing Components Java libraries contain several examples of hierarchical classes related by inheritance User interface component classes in the swing library present one such example

15 Components Base of the component hierarchy is the Component class; includes methods: –getWidth(), getHeight(), setSize(int,int) –setBackground(Color c), getBackground() –setVisible(boolean), setEnabled(boolean) –repaint(Graphics), paint(Graphics) –setFont(Font), getFont() –addMouseListener(MouseListener), addKeyListener(KeyListener)

16 Containers Container class is subclass of Component; most important property is its ability to contain components Methods include: –setLayout(LayoutManager) –add(Component), remove(Component)

17 A little history... First came AWT, Abstract Window Toolkit –Used native components, resulting in subtle platform inconsistencies –Write once, run anywhere -> Write once, debug everywhere Swing library developed as platform- independent solution

18 Characteristics of Swing All components painted on blank windows –all components drawn pixel by pixel –when component changes state (e.g. button pushed), toolkit redraws it Swing has complete control over behavior of components - does not use native components

19 Hierarchy of Swing Components

20 Hierarchy of standard geometric shapes Original AWT classes: integer coordinates –Point –Rectangle –Polygon Java 2 introduced java.awt.geom package - more sophisticated shapes with floating-point coordinates Legacy classes are folded into new hierarchy

21 Hierarchy of standard geometric shapes

22 RectangularShape Superclass for Rectangle2D, RoundRectangle2D, Ellipse2D and Arc2D Methods include: –getCenterX, getCenterY –getMinX, getMinY, getMaxX, getMaxY –getWidth, getHeight –setFrameFromCenter, setFrameFromDiagonal

23 Rectangle2D class Has inner classes Float and Double; hence the name Rectangle2D.Double Rectangle2D is an abstract class; inner classes Float and Double are concrete subclasses that define a small number of methods, including getX(), getY(), getWidth() and getHeight()

24 Template Method design pattern Superclass defines a method that calls primitive operations that a subclass needs to supply Each subclass can supply the primitive operations most appropriate for it Template method contains knowledge of how to combine primitive operations into more complex operation

25 Template method pattern: context An algorithm is applicable for multiple types The algorithm can be broken down into primitive operations The primitive operations can be different for each type The order of the primitive operations doesn't depend on the type

26 Template method pattern: solution Define a superclass that has a method for the algorithm and abstract methods for the primitive operations. Implement the algorithm to call the primitive operations in the appropriate order.

27 Template method pattern: solution Do not define the primitive operations in the superclass, or define them to have appropriate default behavior. Each subclass defines the primitive operations but not the algorithm.

28 Template Method Pattern

29 Rectangle2D and the Template Method Pattern Most of the work is done by Rectangle2D methods, not inner classes; parent class methods call inner class (primitive) methods as needed Example: public boolean contains(double x, double y) { double x0 = getX(); double y0 = getY(); return x >= x0 && y >= y0 && x < x0 + getWidth() && y < y0 + getHeight(); }

30 Template Method pattern & Rectangle2D Pattern name: –AbstractClass –ConcreteClass –templateMethod –primitiveOpn Actual name –Rectangle2D –Rectangle2D.Double –contains() –getX(), getY(), etc.

31 Hierarchy of Exception Classes All exceptions extend class Throwable Throwable has two subclasses: –Error: subclasses of this denote fatal errors (e.g. divide by 0, out of memory, etc.) –Exception: superclass for all exceptions that occur on an application level

32 Exception class Has several subclasses: notable among these is RuntimeException –superclass for all unchecked exceptions –examples include NullPointerException and IndexOutOfBoundsException All subclasses of Exception that are not subclasses of RuntimeException are checked exceptions

33 Checked Exceptions These are the type of exceptions that require either a throws clause or try/catch block Example: IOException and its subclasses

34 Hierarchy of Exception Classes

35 Defining Exception Classes Decide whether or not exception should be checked –Use checked exception if error condition is out of programmer control (e.g. a network failure) –Use unchecked exception if error caused by programmer inattention (e.g. null pointer exception) Subclass Exception or RuntimeException - note that unchecked exceptions must subclass RuntimeException

36 Defining Exception Classes Provide two constructors: public class IllegalFormatException extends Exception { public IllegalFormatException() {} public IllegalFormatException(String reason) { super(reason); } } Throw exception when needed: throw new IllegalFormatException("number expected");