1 Enhanced Class Design -- Introduction  We now examine several features of class design and organization  that can improve reusability and system elegance.

Slides:



Advertisements
Similar presentations
INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
Advertisements

Interfaces A Java interface is a collection
Fields, Constructors, Methods
Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Inheritance Inheritance Reserved word protected Reserved word super
Intro to OOP with Java, C. Thomas Wu Inheritance and Polymorphism
Road Map Introduction to object oriented programming. Classes
Chapter 5: Keyboard I/O & Simple GUI’s Copyright 2002, Matthew Evett. These slides are based on slides copyrighted by John Lewis and William Loftus, 2002,
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Abstract Classes.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Chapter 10 Classes Continued
Interfaces A Java interface is a collection of constants and abstract methods with a name that looks like a class name, i.e. first letter is capitalized.
INF 523Q Chapter 5: Enhancing Classes. 2 b We can now explore various aspects of classes and objects in more detail b Chapter 5 focuses on: object references.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Abstract Classes and Interfaces Lecture 2 – 9/6/2012.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
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.
The Java Programming Language
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
1 Object Oriented Design and UML Class Relationships –Dependency –Aggregation –Interfaces –Inheritance Interfaces Reading for this Lecture: L&L 6.4 – 6.5.
Chapter 6 Object-Oriented Design. © 2004 Pearson Addison-Wesley. All rights reserved6-2 Object-Oriented Design Now we can extend our discussion of the.
Programming in Java CSCI-2220 Object Oriented Programming.
8. Inheritance “Is-a” Relationship. Topics Creating Subclasses Overriding Methods Class Hierarchies Abstract Class Inheritance and GUIs The Timer Class.
Inheritance and Access Control CS 162 (Summer 2009)
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
1 Abstract Classes and Interfaces. 2 The abstract Modifier  The abstract class –Cannot be instantiated –Should be extended and implemented in subclasses.
1 Lecture 9 Enhanced Class Design Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung Institute of Technology.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
Java Programming: From the Ground Up
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao.
Chapter 6 Object-Oriented Design Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/20 The this Reference The this reference allows an object.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Java Software Solutions Lewis and Loftus Chapter 9 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Enhanced Class Design -- Introduction.
Interfaces and Inner Classes
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
1 Enhanced Class Design -- Introduction  We now examine several features of class design and organization that can improve reusability and system elegance.
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.
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
In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The import statement and using prewritten.
SourceAnatomy1 Java Source Anatomy Barb Ericson Georgia Institute of Technology July 2008.
Interfaces. In order to work with a class, you need to understand the public methods  methods, return types,…  after you instantiate, what can you do.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
1 Enhanced Class Design Introduction zWe now examine several features of class design and organization that can improve reusability and system elegance.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
2/23- Interfaces Reference: Java 6.5 and 9.3. PA-4 Review Requirements PA3 – Grading Key PA4 Requirements Doc.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Modern Programming Tools And Techniques-I
Chapter 5: Enhancing Classes
Inheritance and Polymorphism
Chapter 3: Using Methods, Classes, and Objects
Abstract Class As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of ,
CSE 501N Fall ‘09 13: Interfaces and Multiple Representation
Chap 2. Identifiers, Keywords, and Types
Chapter 11 Inheritance and Encapsulation and Polymorphism
Presentation transcript:

1 Enhanced Class Design -- Introduction  We now examine several features of class design and organization  that can improve reusability and system elegance  We will focus on: abstract classes & polymorphism Extending Interfaces

2 Nested Classes  In addition to a class containing data and methods, it can also contain other classes  A class declared within another class is called a nested class Outer Class Nested Class

3 Nested Classes  A nested class has access to the:  variables and methods of the outer class,  even if they are declared private  This makes the implementation of the classes easier because they can easily share information

Protecting the inner class  The nested class can be protected by the outer class from external classes  This is a special relationship 4

5 Nested Classes bytecode file  A nested class produces a separate bytecode file  If a nested class called Inside is declared in an outer class called Outside, two bytecode files will be produced: Outside.class Outside$Inside.class

Inner classes  Nested classes can be declared as static.  in that case, they cannot refer to instance variables or methods declared in the class inner class  A non-static nested class is called an inner class 6

7 Abstract Classes // Class Food is an abstract representation of a food item. abstract class Food { // Returns calories of fat for the food item. public abstract double CaloriesOfFat(); } // class Food

8 Class Pepporoni // Class Pepperoni is derived from an abstract class // and implements its method. class Pepperoni extends Food { private double CaloriesOfFat = 100; // Returns the number of fat calories. public double CaloriesOfFat() { return CaloriesOfFat; } // method } // class Pepperoni

9 Dinner class public class Dinner { // Creates a Pepperoni object and invokes its method. public static void main (String[] args) { Pepperoni slice = new Pepperoni(); System.out.println (slice.CaloriesOfFat()); } // method main } // class Dinner

10 Abstract Classes  See Printer.java File int NumberOfCharacters Text_File Binary_File =.class file Image_File

11 Interfaces interface constants and abstract methods  A Java interface is a collection of constants and abstract methods  Let’s review an example:

12 Interfaces public interface Doable { public abstract void doThis(); public abstract int doThat(); public abstract void doThis2 (float value, char ch); public boolean doTheOther (int num); } interface is a reserved word interface is a reserved word A semicolon immediately follows each method header

13 Interfaces public class CanDo implements Doable { public void doThis () { // whatever } public void doThat () { // whatever } // etc. } implements is a reserved word Each method listed in Doable is given a definition

interface, Geometry  The interface, Geometry, consists of  one static constant and two abstract methods. 1.public interface Geometry 2.{ 3.public static final double PI = ; // a constant 4.public abstract double area(); abstract double perimeter(); 5.public abstract double perimeter(); 6.}

Interfaces Unlike a class: 1.all methods of an interface are abstract, i.e., 2.there are no implementations at all, and 3.an interface has no instance variables.  Like an abstract class,  an interface cannot be instantiated.

 In contrast to an abstract class,  a class does not extend an interface.  Instead, a class implements an interface.

Problem Statement: Define Circle, Square, and Triangle classes implements the Geometry interface. each of which implements the Geometry interface. Java Solution:  The following classes implement Geometry, therefore, to implement the area() and perimeter() methods.  each class is required to implement the area() and perimeter() methods.

Circle 1.public class Circle implements Geometry 2.{ 3. private double radius; public Circle() // constructdor 6. { 7. radius = 0.0; 8. } // constructdor 9. public Circle (double r) // constructdor 10. { 11. radius = r; 12. } 13. public double perimeter() // method 14. { 15. return 2*PI*radius; 16. } 17. public double area() // method 18. { 19. return PI*radius*radius; 20. }}

Class Square 1.public class Square implements Geometry 2.{ private double side; public Square() // CONSTRUCTORS 5. { 6. side = 0.0; 7. } 8. public Square (double s) 9. { 10. side = s; 11. } 12. public double perimeter() // METHODS 13. { 14. return 4*side; 15. } 16. public double area() 17. { 18. return side*side; 19. } 20.}

CLASS Triangle public class Triangle implements Geometry 1.{ // three sides a,b,c 2. // three sides a,b,c 3. private double a,b,c; public Triangle (double a1, 1. double b1, double c1) 2. { 3. a = a1; 4. b = b1; 5. c = c1; 6. } public double perimeter() 16. { 17. return a+b+c; 18. } 19. public double area() 20. { 21. double s =(a+b+c)/2.0; 22. return 23. Math.sqrt(s*(s-a)*(s-b)*(s-c)); 24. } 25. }

The Comparable Interface  Java also provides a large number of ready-made interfaces.  One of the most useful Java-supplied interfaces  is the Comparable interface.   Comparable is an interface with just one method,  compareTo(...):

interface Comparable public interface Comparable { public abstract int compareTo(Object o); } returns an integer and compareTo(...) returns an integer and accepts any Object reference as an argument. 22

The Comparable Interface  A class that implements the Comparable interface implements compareTo(...) so that a.CompareTo(b) returns a negative integer, if a is “less than” b, a.CompareTo(b) returns 0, if a “equals” b, and a.CompareTo(b) returns a positive integer, if a is “greater than” b.  A class that implements Comparable is lets its clients know that its objects can be “compared”.

The Comparable Interface Problem statement:  Define a Production hierarchy with Film and Play as child classes.  Film and Play implement the Comparable interface.

A Film class has attributes ( instance variables):  title,  director,  screenwriter, and  total box office gross, in millions of dollars adjusted for inflation. The methods of a Film class include:  constructors,  getters and setters, and  a method that displays the values of each attribute. 25

Like a Film class, a Play class has:  a title,  a director, and  a writer or playwright.  Additionally, a Play object holds the number of performances of a play.  The Play methods are:  getter and setter methods, and  a method that displays the values of each attribute. 26

A Play class and a Film class - Implement Comparable Interface and extend Productions  27

Inheritance by Factoring  The Play class and the Film class are very similar  and share many of the same attributes and methods.  They both will extend another class Production - it will contain the methods and attributes common to both.  This is called “Inheritance by Factoring” 28

Inheritance Hierarchy Play extends Production; Film extends Production They also both implement the Comparable Interface 29

Because Play implements Comparable, Because Play implements Comparable, Play must implement compareTo(…). public class Play extends Production implements Comparable // OTHER METHODS { // OTHER METHODS public int compareTo(Object p) {// from the Comparable interface public int compareTo(Object p) {// from the Comparable interface if ( ! (p instanceof Play) ) // p must BE A PLAY OBJECT if ( ! (p instanceof Play) ) // p must BE A PLAY OBJECT { System.out.println("Error: Object does not belong to Play"); System.out.println("Error: Object does not belong to Play"); System.exit(0); System.exit(0); } // p must be cast to TYPE Play if (performances < ((Play) p).performances) { return -1; if (performances < ((Play) p).performances) { return -1; if (performances > (( Play )p).performances) if (performances > (( Play )p).performances) return 1; return 1; return 0; return 0; } } }

Examine the Code - the instanceOf operator // method defined in the Comparable interface public int compareTo(Object p) public int compareTo(Object p) // p must BE A PLAY OBJECT if ( ! (p instanceof Play) ) { if ( ! (p instanceof Play) ) { System.out.println("Error: Object does not belong to Play class"); System.out.println("Error: Object does not belong to Play class"); System.exit(0); // exits the program System.exit(0); // exits the program } 31

Examine Code: Casting Objects // p must be cast to TYPE Play if ( performances < ((Play) p).performances) if ( performances < ((Play) p).performances) { return -1; // number of performances less than { return -1; // number of performances less than if ( performances > (( Play )p).performances ) if ( performances > (( Play )p).performances ) return 1; ; // number of performances greater than return 1; ; // number of performances greater than // returns they are equal // returns they are equal return 0; return 0; } } } 32

Comparable interface FILM  The following compareTo() method is located in a class of type FILM Film class  The Film class implements Comparable and extends the Production class 33

COMPARISON OF BOX OFFICE GROSSES FOR THE TWO FILM OBJECTS, returning 0, 1 or -1 public int compareTo(Object p )// “p” should be a Film object public int compareTo(Object p )// “p” should be a Film object { if ( !(p instanceof Film)) { // p must BE A FILM OBJECT if ( !(p instanceof Film)) { // p must BE A FILM OBJECT System.out.println("Error: object must belong to Film"); System.out.println("Error: object must belong to Film"); System.exit(0); System.exit(0); } // Now cast p to a FILM object and compare values // Now cast p to a FILM object and compare values if (boxOfficeGross < ((Film) p ).boxOfficeGross ) return -1; if (boxOfficeGross < ((Film) p ).boxOfficeGross ) return -1; if (boxOfficeGross > ((Film)p).boxOfficeGross) return 1; if (boxOfficeGross > ((Film)p).boxOfficeGross) return 1;}

35 Interfaces & Constants  interface constants require nothing special of the implementing class  Constants in an interface can be used in the implementing class as if they were declared locally  This feature provides a convenient technique for distributing common constant values among multiple classes eg. pi =  The value of pi =

36 Interfaces  An interface can extend other interfaces  The child interface inherits the constants and abstract methods of the parent  A class that implements the child interface must define all methods in both the parent and child

Class and Interfaces Hierarchy  Note that the interface hierarchy and the class hierarchy are distinct.  The interface hierarchy does not define an ISA relationship.  It’s ability to speak is a functionality it is given. 37

38 Interfaces - SUMMARY  An interface can be implemented by multiple classes  Each implementing class can provide their own unique version of the method definitions  An interface is not a class, and cannot be used to instantiate an object of the Interface  An interface is not part of the class hierarchy  A class can be derived from a base class and implement one or more interfaces

39 Interfaces  A class that implements multiple interfaces specifies all of them in its header, separated by commas  The ability to implement multiple interfaces provides many of the features of multiple inheritance,  the ability to derive one class from two or more parents  Java does not support multiple inheritance

40  Some details on when to use and interface or an abstract class:  If Abstract class A requires abstract methods - should classes B and C extend it or implement it ? Rules:  If all the methods in B must be implemented differently implemented differently from the same methods in C, make A an interface.

INTERFACES  The methods in A then require that these methods must be implemented in B and C.  A can act as the super type, listing the methods that MUST be implemented in B & C. 41

42 Interfaces - Review  Interfaces have the same access levels as classes, public and package.  A class can implement more one interface.  If a parent class implements an interface,  its child classes automatically implements the interface. defines a type.  An interface, like a class, defines a type.

43 Interfaces – Static Fields 1. Fields can be declared in an interface. (Constants) 2. All fields are public, static and final. (Constants) 3. Declaring a field to be any other access level except public is a compile error. 4. If no access level is given, it defaults to public. 5. If a field is not explicitly declared to be static or final, the field is still static and final.

44 Interfaces - Example // CONTAINS STATIC CONSTANT interface WithStatic // CONTAINS STATIC CONSTANTS { public static final int EXPLICIT = 42; // VALID public static int IS_FINAL = 12; // VALID public int IS_FINAL_AND_STATIC = 3; // VALID protected int COMPILE_ERROR = 4; public int NO_VALUE_COMPILE_ERROR; }

45 STATIC FIELDS - EXAMPLE class Radio implements WithStatic { public void AM(){ System.out.println( IS_FINAL ) System.out.println( IS_FINAL ); } } // close class class Test { public static void main( String args[] ) { System.out.println( WithStatic.EXPLICIT ); // uses interface name ); // uses class name System.out.println( Radio.EXPLICIT ); // uses class name // create object of class Radio megaBass = new Radio(); // create object of class // uses object name System.out.println( megaBass.EXPLICIT ); // uses object name megaBass.AM(); } }

46 Method Name Conflicts A class implements two interfaces that each have a method with the same name, Square():  If both Square() methods in each interface have different signatures( # and type of parameters), two overloaded methods.  then the class implements two overloaded methods.  If both methods have the same signature and the same return type,  then the class implements only the one square() method.

47 Method Name Conflicts different return types  If both Square() methods have the same signature and different return types, can not implement both interfaces.  then the class can not implement both interfaces.

Conflicting interfaces  If both methods have the 1. same signature, 2. same return type  but differ in the  types of exceptions they throw,  then the class implements only the one method,  but it must contain the exceptions of both methods. 48

 If a class implements two interfaces that each have a field with the same name, say bar,  then the class must use the full interface names for the fields. 49

50 Extending Interfaces One interface can inherit from another interface, supporting multiple inheritance. interface Door { public void open(); public void close(); } interface LockableDoor extends Door { public void lock(); public void unlock(); }

51 Extending Interfaces class CarDoor implements LockableDoor { private boolean isLocked = false; // methods inherited from Interface DOOR public void open() { { if ( !isLocked) System.out.println( "Enter the car" ); } public void close() public void close() { { System.out.println( "Closing the door"); }

52 Extending Interfaces // methods inherited from Lockable door public void lock() { isLocked = true; } public void unlock() { isLocked = false; } } //close class

Some issues with extending Interaces public class TestDoor { public static void main( String[] args ) { Door d = new CarDoor(); d.open(); // open() is in Door Interface Compile error –lock() not in Door Interface //Compile error –lock() not in Door Interface d.lock(); // lock is in Lockable interface // must cast d to a lockable door // must cast d to a lockable door LockableDoor better = (LockableDoor) d; better.lock(//OK better.lock(); //OK } 53

54 Packages  A Java package is a collection of classes  The classes in a package may or may not be related by inheritance  A package is used to group similar and interdependent classes together

package The Java API is composed of multiple packages The import statement is used to assert that a particular program will use classes from a particular package 55

56 Packages  A programmer can define a package and add classes to it  The package statement is used to specify that all classes defined in a file belong to a particular package  The syntax of the package statement is: package package-name ; e.g. package Graph; package Graph;  It must be located at the top of a file, and there can be only one package statement per file

57 Packages  The classes must be organized in the directory structure  such that they can be found when referenced by an import statement  The import statement specifies particular classes, or an entire package of classes, that can be used in that program

58 Packages  As a rule of thumb, if you will use only one class from a package, import that class specifically  imports a single class in the util package import Java.util.Iterator import Java.util.Iterator *  If two or more classes will be used, use the * wildcard character in the import statement to provide access to all classes in the package  import java.util.*; // imports all the classes in the package