1 / 54

Enhanced Class Design -- Introduction

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 formal Java interfaces packages. Outer Class. Nested Class. Nested Classes.

jersey
Download Presentation

Enhanced Class Design -- Introduction

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

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 • formal Java interfaces • packages

  2. Outer Class Nested Class 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

  3. Nested Classes • A nested class has access to the variables and methods of the outer class, even if they are declared private • In certain situations this makes the implementation of the classes easier because they can easily share information • Furthermore, the nested class can be protected by the outer class from external use • This is a special relationship and should be used with care

  4. Nested Classes • 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 • Nested classes can be declared as static, in which case they cannot refer to instance variables or methods • A non-static nested class is called an inner class

  5. Abstract Classes • An abstract class is used in a class hierarchy to organize common features at appropriate levels • An abstract method has no implementation, just a name and signature • An abstract class contains abstract methods • Any class that contains an abstract method is by definition abstract • An abstract class cannot be instantiated

  6. Abstract Classes – Some rules • The modifier abstract is used to define abstract classes and methods • The child classes of the abstract class are expected to define implementations for the abstract methods in ways appropriate for them • If a child class does not define all abstract methods of the parent, then the child is also abstract • An abstract class is often too generic to be of use by itself

  7. Food Beans Franks Pepperoni Abstract Classes • See Dinner.java

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

  9. 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

  10. 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

  11. File int NumberOfCharacters Binary_File Text_File Image_File Abstract Classes • See Printer.java

  12. Abstract Classes • An abstract method cannot be declared as final, because it must be overridden in a child class • An abstract method cannot be declared as static, because it cannot be invoked without an implementation • Abstract classes are placeholders that help organize information and provide a base for polymorphic references • Abstract classes can contain methods with full definitions.

  13. Interfaces • Till now we have used the term interface to mean the set of service methods provided by an object. • That is, the set of methods that can be invoked through an object define the way the rest of the system interacts, or interfaces, with that object. • The Java language has an interface construct that formalizes this concept • A Java interface is a collection of constants and abstract methods

  14. Basics of Interfaces Consists of : • methods that are public and abstract • fields that are public, static, and final • Implemented by a class that declares it implements the interface and • the class defines implementations for all the interface methods • A class can implement multiple interfaces

  15. Interfaces • A class that implements an interface must provide implementations for all of the methods defined in the interface. • This relationship is specified in the header of the class: class class-name implements interface-name { } See Soap_Box.java

  16. Interfaces • A Java interface is a collection of abstract methods and constants • An interface is used to formally define a set of methods that a class will implement

  17. interface is a reserved word A semicolon immediately follows each method header Interfaces None of the methods in an interface are given a definition (body) public interface Doable { public abstract void doThis(); public abstract int doThat(); public abstract void doThis2 (float value, char ch); public abstract boolean doTheOther (int num); }

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

  19. Interfaces • An interface cannot be instantiated • Methods in an interface have public visibility by default • A class formally implements an interface by • stating so in the class header • providing implementations for each abstract method in the interface • If a class asserts that it implements an interface, it must define all methods in the interface or the compiler will produce errors.

  20. Interfaces • A class that implements an interface can implement other methods as well • See Speaker.javaPhilosopher.java • See Dog.java • A class can implement multiple interfaces The interfaces are listed in the implements clause, separated by commas • The class must implement all methods in all interfaces listed in the header

  21. Interface Philosopher //Interface Philosopher lists the methods that must be //defined by any class that implements the interface. interface Philosopher { //============================ // Should be defined to return a statement made by // particular philosopher //============================ public abstract String pontificate(); } // interface Philosopher

  22. // Class Kant represents the teachings of philosopher //Immanual Kant. It implements the Philosopher interface, //and therefore must define method pontificate. class Kant implements Philosopher { //============================ // Returns a key philosophical statement by Kant. //============================ public String pontificate() { return "Follow the Categorical Imperative!"; } // method pontificate } // class Kant

  23. Class Soap_Box // driver class public class Soap_Box { /============================ //Creates a Kant object and calls pontificate method . //============================ public static void main (String[] args) { Kant immanual = new Kant(); System.out.println (immanual.pontificate()); } // method main } // class Soap_Box

  24. Polymorphism via Interfaces • An interface name can be used as the type of an object reference variable Doable obj; obj = new Cando() • The obj reference can point to any object of any class that implements the Doableinterface • The version of doThisthat the following line invokes depends on the type of object that objis referring to: obj.doThis();

  25. Polymorphism via Interfaces • That reference is polymorphic, which can be defined as "having many forms" • That line of code might execute different methods at different times if the object that objpoints to changes. See Talking.java • Polymorphic references are often resolved at run time; this is called dynamic binding though there is a way to have it done at compile time we will look at later

  26. Interfaces //*********************************************** Demonstrates the declaration of an interface. Dog and Philosopher will implement it and provide implementations for the speak and announce methods ***********************************************/interface Speaker{ public abstract void speak (); public abstract void announce (String str);}

  27. //******************************************************** // Dog provides implementation for the methods in the Speaker interface //******************************************************** class Dog implements Speaker{//-----------------------------------------------------------------// Prints this dog's philosophy.//----------------------------------------------------------------- public void speak () { System.out.println ("woof"); }//-----------------------------------------------------------------// Prints this dog's philosophy and the specified announcement.//----------------------------------------------------------------- public void announce (String announcement) { System.out.println ("woof: " + announcement); }}

  28. //******************************************************** // Philosopher provides implementation for the methods in the Speaker interface and another method of its own //******************************************************** • class Philosopher implements Speaker{ private String philosophy; //----------------------------------------------------------------- // Establishes this philosopher's philosophy. //----------------------------------------------------------------- public Philosopher (String philosophy) { this.philosophy = philosophy; } //----------------------------------------------------------------- // Prints this philosophers's philosophy. //----------------------------------------------------------------- public void speak () { System.out.println (philosophy); }

  29. //----------------------------------------------------------------- // Prints the specified announcement. //----------------------------------------------------------------- public void announce (String announcement) { System.out.println (announcement); } //----------------------------------------------------------------- // Prints this philosophers's philosophy multiple times. //-----------------------------------------------------------------public void pontificate () { for (int count=1; count <= 5; count++) System.out.println (philosophy); }}

  30. class Talking{//-----------------------------------------------------------------// Instantiates two objects using an interface reference and// invokes one of the common methods. Then casts the interface// reference into a class reference to invoke its unique method.//----------------------------------------------------------------- public static void main (String[] args) {Speaker current; // Speaker is an Interfacecurrent = new Dog(); // class dog implements the interface current.speak(); // current is now a dog current = new Philosopher ("I think, therefore I am."); current.speak(); // current is now a philosopher ((Philosopher) current).pontificate(); }}

  31. Interfaces • An interface name can be used as a generic reference type name • A reference to any object of any class that implements that interface is compatible with that type • For example, if Philosopher is the name of an interface, it can be used as the type of a parameter to a method • An object of any class that implements Philosopher can be passed to that method

  32. interfaces • E.g: public void Ideas(Philosopher p) { // some code } • Any class implementing the Philosopher interface can be sent as a parameter to this method.

  33. Interfaces & Constants • Unlike interface methods, 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

  34. Interfaces • An interface can be derived from another interface, using the extends reserved word • 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 • Note that the interface hierarchy and the class hierarchy are distinct. The interface hierarchy does not define an ISA relationship. A Dog is not a Speaker. It’s ability to speak is a functionality it is given.

  35. 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 • An interface is not part of the class hierarchy • A class can be derived from a base class and implement one or more interfaces

  36. 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

  37. Interfaces VS Abstract Classes • Note the similarities between interfaces and abstract classes • Both define abstract methods that are given definitions by a particular class • Both can be used as generic type names for references • However, a class can implement multiple interfaces, but can only be derived from one class.

  38. Interfaces - Details • Let B & C be classes. Assume that we make A the parent class of B and C so A can hold the methods and fields that are common between B and C. • Sometimes a method in B is so different from the same method in C there is no shared implementation possible in A. We can make A an abstract class. • The methods in A then determine which methods must be implemented in B and C.

  39. Interfaces - Details • A can act as the super type, listing the methods that should be implemented in B & C. •  If all the methods in B must be implemented differently from the same methods in C, make A an interface. • Interfaces can specify public methods but can not implement them. Thus, one can not create an object from an interface. • Interfaces can have fields. All fields in an interface are final and static even if they are not explicitly declared as such.

  40. Interfaces - Details • 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. • An interface, like a class, defines a type. • Fields, variables, and parameters can be declared to be of a type defined by an interface.,

  41. Interfaces – Static Fields • Constants – also called fields - an be declared in an interface. • All constants are public static and final. • Declaring a constant to be any other access level except public is a compile error. • If no access level is given, it defaults to public. • If a constant is not explicitly declared to be static or final, the field is still static and final.

  42. Interfaces - Example interface WithStatic { public static final int EXPLICIT = 42; public static int IS_FINAL =    12;    public int IS_FINAL_AND_STATIC = 3;    protected int COMPILE_ERROR = 4;   public int NO_VALUE_COMPILE_ERROR;}

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

  44. 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();}

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

  46. Extending Interfaces public void lock() { isLocked = true; } public void unlock() { isLocked = false; } } //close class public class TestDoor { public static void main( String[] args ) { Door d = new CarDoor(); d.open(); d.lock(); //Compile error LockableDoor better = (LockableDoor) d; better.lock(); //OK } }

  47. Method Name Conflicts A class implements two interfaces that each have a method with the same name, Square(): • If both Square() methods have different signatures, 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.

  48. Method Name Conflicts • If both Square() methods have the same signature and different return types, then the class can not implement both interfaces. • If both methods have the same signature, same return type but differin the types of exceptions they throw, then the class implements only the one method, but it must contain the exceptions of both methods. • If a class implements two interfaces that each have a field with the same name, say bar, then the class must  use the full names for the fields.

  49. Interfaces • The Java standard class library contains many interfaces that are helpful in certain situations. • The Comparableinterface contains an abstract method called compareTo, which is used to compare to objects. • The Stringclass implementsComparablewhich gives us the ability to put strings in alphabetical order

  50. Comparable • It is advisable to override the compareTo method in your classes if you wish to compare two objects according to some specifaction. E.g. comparing SSN’s in the student class.

More Related