Object-Oriented Design CSC 212. Announcements Ask more questions! If I am not making myself clear, it is your opportunity to explain what is confusing.

Slides:



Advertisements
Similar presentations
Object Oriented Programming with Java
Advertisements

Object Oriented Programming
SUMMARY: abstract classes and interfaces 1 Make a class abstract so instances of it cannot be created. Make a method abstract so it must be overridden.
Inheritance Inheritance Reserved word protected Reserved word super
Objectives Introduction to Inheritance and Composition (Subclasses and SuperClasses) Overriding (and extending), and inheriting methods and constructors.
LECTURE 7: INHERITANCE CSC 212 – Data Structures.
ITEC200 – Week03 Inheritance and Class Hierarchies.
CS 106 Introduction to Computer Science I 11 / 26 / 2007 Instructor: Michael Eckmann.
1 Lecture 3 Inheritance. 2 A class that is inherited is called superclass The class that inherits is called subclass A subclass is a specialized version.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Chapter 10 Classes Continued
Abstract Classes and Interfaces
Question of the Day  Write valid mathematical equation using: one addition operator (‘+’) one equality operator (‘=’)  Should have equal values.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
CSC 212 Object-Oriented Programming and Java Part 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.
2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and.
Basic Java Syntax CSE301 University of Sunderland Harry R Erwin, PhD.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
Question of the Day  Write valid mathematical equation using: one addition operator (‘+’) one equality operator (‘=’)  Should have equal values.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
CSC 212 – Data Structures Lecture 11: More Inheritance & Generic Types.
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.
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.
Question of the Day  There are two escalators at each subway stop. One going up & one down.  Whenever an escalator needs to be fixed, they almost always.
Programming in Java CSCI-2220 Object Oriented Programming.
LECTURE 9: INTERFACES & ABSTRACT CLASSES CSC 212 – Data Structures.
1 Interfaces and Abstract Classes Chapter Objectives You will be able to: Write Interface definitions and class definitions that implement them.
Question of the Day  Thieves guild states it will sell to members: lock picking kits  $0.67 each 40’ rope  $2.12 each Wire cutters  $4.49 each How.
Problem of the Day  What is the smallest positive integer that cannot be defined in less than twenty-five syllables?
Question of the Day  Thieves guild states it will sell to members: lock picking kits  $0.67 each 40’ rope  $2.12 each Wire cutters  $4.49 each How.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Object Oriented Programming
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
 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
Question of the Day  There are two escalators at each subway stop. One going up & one down.  Whenever an escalator needs to be fixed, they almost always.
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.
AD Lecture #1 Object Oriented Programming Three Main Principles 1 Inheritance Encapsulation Polymorphism.
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.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
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.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
Modern Programming Tools And Techniques-I
Web Design & Development Lecture 9
Inheritance and Polymorphism
Inheritance, Polymorphism, and Interfaces. Oh My
Abstract classes and interfaces
Extending Classes.
Introduction interface in Java is a blueprint of a class. It has static constants and abstract methods only. An interface is a way to describe what classes.
Object Oriented Programming
Abstract classes and interfaces
Chapter 11 Inheritance and Encapsulation and Polymorphism
Presentation transcript:

Object-Oriented Design CSC 212

Announcements Ask more questions! If I am not making myself clear, it is your opportunity to explain what is confusing you (and my chance to try and explain it differently and help solve your confusion) Get additional Java review now  Homework #1 on web; due in one week

Object Inheritance Review Subclass represents es can extend or specialize the superclass Use extends to declare a subclass public class subclass extends superclass {...} public class Robin extends Bird {...} public class Van extends Automobile {...} public class ProfHertz extends Genius {...}  Subclass inherits non-private fields and methods  As if fields & methods were pasted into subclass code

Object Inheritance Review Inheritance represents “is a” relationship  E.g., Robin “is a” Bird; Van “is a” Automobile; Prof. Hertz “is a” Genius  Sorry, I couldn’t resist the last example Subclass can specialize superclass  Subclass can add functionality  Subclass can define additional data  Subclass can specialize how instances operate

Reusing Fields in Subclasses Subclasses can hide superclass’s fields  Subclass defines field with identical name  Field from superclass also exists in subclass super. accesses superclass’s field Which field Java will access? What does this depend on?

Field Hiding Example public class SuperClass { public SuperClass() { } protected String myString = “SUPERSTRING”; public String getMyString() { return myString; } } public class SubClass extends SuperClass { public SubClass() { } protected String myString = “substring”; public String getMyString() { return myString; } public String getOldString() { return super.myString; }

Field Hiding Example public static void main(String[] args) { SubClass sub = new SubClass(); SuperClass supr = sub; System.out.println(sub.getMyString()); System.out.println(supr.getMyString()); System.out.println(sub.myString); System.out.println(supr.myString); System.out.println(sub.getOldString()); }

Reusing Names Review Two ways of reusing method names:  Overloading – same name, different signature  Overriding – same name, same signature  Java calls the method appropriate to the actual object instance, NOT the variable type Reusing field name hides inherited field  Both fields exist within the class  Java uses field appropriate to variable type

Daily Quiz #1 Do problem R-2.10 (p. 96) from the book

Polygons Consider polygon classes:  Rectangle, Square, Triangle, … Want generic Polygon class  Superclass for all these classes  Make arrays of Polygons possible  Enables Polygon as method parameter

Polygons Polygons have at least two common methods:  float area() and float circumference()  But their implementation is class specific How can we do this?

Polygon Class public abstract class Polygon { public abstract double area(); public abstract double circumference(); public boolean isPlanar() { return true; } } Abstract methods have no body  Serve as placeholder for subclasses to define  Guarantee minimal class functionality

Abstract Class Abstract classes cannot be instantiated  Any class could be declared abstract Subclass need not override all abstract methods  But subclass will also be abstract Can instantiate subclasses of abstract class only if all inherited abstract methods overriden

Square Class public class Square extends Polygon { protected double side; public Square() { this(1.0); } public Square(double length) { side=length; } public double area() { return side * side; } public double circumference() { return side * 4; } public double getLength() { return side; } public double getWidth() { return side; } } Can we instantiate Square ?

Benefits of Abstract Classes Polygon[] polys = new Polygon[3]; polys[0] = new Square(2.0); polys[1] = new Triangle(...); polys[2] = new Square(5.6); double total_area=0.0; for (int i=0; i<shapes.length; i++) total_area += shapes[i].area();

Abstract Class Summary Abstract classes can contain fields, abstract methods, and normal methods  Superclass can specify common functionality  Subclasses required to implement methods  Any class with abstract method(s) is abstract

Abstract Class Summary Abstract class cannot be instantiated  But class can be extended  Subclasses could then be instantiated Declaring methods abstract forces subclasses to implement them  Can be good  Can be bad

Public Methods (Explicitly Stated) (Important!) Interfaces Interface is Java’s way to define an ADT  Design document for external class features Class Details (HIDDEN!) (What do I care?)

Interfaces Interfaces declare public abstract methods  Cannot define any other methods Interfaces can declare fields  Fields have constant value (public static final) Classes implement interfaces  Class can implement more than 1 interface  Must implement all the interfaces’ methods

Methods in an Interface All methods are abstract  Adding abstract qualifier is optional Methods cannot have any implementation  Implementation left strictly to Classes Methods public by default  Methods cannot be native, static, synchronized, or final

Goal of Interface We want Polygons to be drawable  But want to make other classes drawable, too Could make an abstract Drawable class  Classes can’t extend Polygon AND Drawable Solution: Make Drawable an interface!  Provides way of multiple inheritence

Declaring Interfaces public interface Drawable { public void setColor(Color c); public void setPosition(double x, double y); public void draw(Graphics g); } public interface TransparentDrawable extends Drawable { public void setTransparency(int tLevel); }

Using Interfaces public class DrawableSquare extends Square implements Drawable { private Color c; private double x,y; public DrawableSquare(double length) { super(length); } public void setColor(Color col) { c = col; } public void setPosition (double x_pos, double y_pos) { x=x_pos; y=y_pos; } public void draw(Graphics g) { g.drawRect(x, y, side, side, c); } }

Benefits of Interfaces public void drawRed(Drawable d, Graphics g) { d.setColor(red); d.draw(g); } Which of these calls are legal? drawRed(new Square(4), g); drawRed(new SquareDrawable(4), g); drawRed(new TriangleDrawable(…), g); drawRed(new DrawableIcon(…), g);

Last Word on Interfaces Interfaces can have sub-interfaces  Sub-interface extends its super-interface Inherits all abstract methods and static final fields Can then further declare more to list  Classes implementing sub-interface automatically implement super-interface Will need to implement all the abstract methods

Typecasting Polygon square = new Sqare(); double r = square.getLength(); Won’t compile!! Variable square is declared to be Polygon  Can only use methods defined on Polygon  Declaration specifies which methods can run  Actual type determines which methods do run

How To Get a Square from a Polygon Polygon c = new Square(); double l = ((Square)c).getLength(); Typecasting forces c to act like square This now compiles (and works) But be careful with this power  This also compiles, but will not work: int i = 9; double l = ((Square)i).getLength();

Widening Conversions String s = new String(“hello”); Object obj; obj = s; This is a widening conversion  Assigns a String to variable of superclass type Widening conversions are always legal  By inheritance, a String “is a” Object  Do not need to perform any typecasting

Narrowing Conversions String s = new String(“bye”); Object obj = s; String t = obj; // NO! NO! NO! Java cannot perform narrowing coversions  Assigning superclass variable to subclass variable  Cannot always tell if this is legal  Must be done using typecasting: String t = ((String)obj);