680 likes | 1.15k Views
Chapter 8 Interfaces and Nested Classes. Outline. Defining and Using Interfaces Differences between Interfaces and Abstract Classes Using Multiple Interfaces Interface as a Data Type Extending an Interface Pre-defined Interfaces Nested Interfaces and Nested Classes Static Nested Classes
E N D
Chapter 8 Interfaces and Nested Classes
Outline Defining and Using Interfaces Differences between Interfaces and Abstract Classes Using Multiple Interfaces Interface as a Data Type Extending an Interface Pre-defined Interfaces Nested Interfaces and Nested Classes Static Nested Classes Inner Classes Anonymous Classes Summary Chapter 8 Interfaces and Nested Classes
What are Interfaces? An interface is a collection of abstract methods that describe a certain behavior – it represents a type. Create an interface by using the interface keyword followed by the interface name. An interface can contain one or more abstractmethods. A class that implements an interface must define all the abstract methods in that interface; otherwise, it must be declared abstract. Chapter 8 Interfaces and Nested Classes
Example of an Interface public interface Smartness { public abstract void doSomethingSmart(); } public SmartHome extends Home implementsSmartness { public void doSomethingSmart() { // code to turn on light and room heater // when person enters room // code to turn off light and heater // when person leaves room } } An interface called Smartness: Class SmartHome implements this interface: Chapter 8 Interfaces and Nested Classes
Defining an Interface An interface can contain abstract methods and constant fields. The first letter of the interface name should be capitalized. Constants in an interface are implicitly public, static and final. All methods in an interface are implicitly public and abstract. Modifiers protected and private cannot be used in an interface. Static methods and instance fields are not allowed in interfaces. Interfaces cannot be instantiated. Chapter 8 Interfaces and Nested Classes
Example public interface Rotatable { int SECONDS_PER_MINUTE = 60; // constant field // abstract methods double angularSpeed(); void rotate(double angularSpeed); } • Interface Rotatable: Chapter 8 Interfaces and Nested Classes
Exercise interface NewInterface { public static final float ALPHA = 5.5f; private float BETA = 1.2f; // methods private void method1(int i); void method2(int); public static int method3(float j); int method4(float k); public abstract method5(); } • Find the errors in the interface declaration below: Chapter 8 Interfaces and Nested Classes
Palette: The ColorMixable Interface import java.awt.*; public interface ColorMixable { void setColor(Color c); void mixColor(Color c); Color getColor(); } Is a behavior called “color mixable”, which is the ability to mix colors to make new colors: Chapter 8 Interfaces and Nested Classes
Using an Interface • Two important points to remember: • A class that implements an interface must provide the body for all the methods in that interface; otherwise, the class must be declared abstract. • A class that implements an interface can use the constant fields in the interface as if they were defined in the class itself. Chapter 8 Interfaces and Nested Classes
Using an Interface continued public class Wheel implements Rotatable { private int revolutionsPerMinute = 10; public double angularSpeed() { double speed = (revolutionsPerMinute * 2 * Math.PI)/SECONDS_PER_MINUTE; return speed; } public void rotate(double angularSpeed) { // code to move wheel by the angular speed } // other methods } Class Wheel implements interface Rotatable: Chapter 8 Interfaces and Nested Classes
Using an Interface continued public abstract class RotatingToyimplements Rotatable { // some code } Suppose that class RotatingToy implements Rotatable but does not define one or both of the methods in this interface, then RotatingToy must be made abstract: Chapter 8 Interfaces and Nested Classes
Palette: The ColoredEllipse Class public class ColoredEllipse extends Ellipse2D.Float { protected Color ellipseColor; public ColoredEllipse() { this(0, 0, 0, 0); } public ColoredEllipse(float x, float y, float width, float height) { super(x, y, width, height); // set initial color to white ellipseColor = new Color(255, 255, 255); } } Used to create colored ellipses: Chapter 8 Interfaces and Nested Classes
Palette: The ColoredEllipse Class continued public class ColoredEllipse extends Ellipse2D.Floatimplements ColorMixable{ // field and constructors on preceding slide // implements method getColor to retrieve field ellipseColor // implements method setColor to modify field ellipseColor // implements the abstract mixColor method in ColorMixable public void mixColor(Color c) { // create a new color int red = (ellipseColor.getRed() + c.getRed())/2; int green = (ellipseColor.getGreen() + c.getGreen())/2; int blue = (ellipseColor.getBlue() + c.getBlue())/2; ellipseColor = new Color(red, green, blue); } } Modified to implement the interface ColorMixable: Chapter 8 Interfaces and Nested Classes
Palette: The ColoredRectangle Class public class ColoredRectangle extends Rectangle2D.Floatimplements ColorMixable { // field and constructors // implements method setColor to modify field rectangleColor // implements method getColor to return field rectangleColor // different from the mixColor method in ColoredEllipse public void mixColor(Color c) { // create a new color int red = (Math.abs(rectangleColor.getRed() - c.getRed()))/2; int green = (Math.abs(rectangleColor.getGreen() - c.getGreen()))/2; int blue = (Math.abs(rectangleColor.getBlue() - c.getBlue()))/2; rectangleColor = new Color(red, green, blue); } } Has a different mixColor method (subtracts colors to create a new color): Chapter 8 Interfaces and Nested Classes
Diagram Showing the Classes and Interfaces in the Palette Program Chapter 8 Interfaces and Nested Classes
Differences Between Interfaces and Abstract Classes • Unlike an abstract class, an interface cannot contain any constructors. • It is not necessary for an abstract class to have any abstract methods; however, an interface contains only abstract methods. • An abstract class can contain instance, static and constant fields, whereas an interface can contain only constant fields. • The methods in an abstract class can be declared using any of the access modifiers; all methods of an interface must be public. • An abstract class can contain static methods, but an interface cannot. Chapter 8 Interfaces and Nested Classes
Using Multiple Interfaces public interface Whistler { void whistle(); } • A class can implement any number of interfaces and must define the methods that are present in all of these interfaces. • Example: • Interface Whistler: • Class SpinningTop implements both Rotatable and Whistler interfaces: • Must define methods angularSpeed, rotate, and whistle, or be declared abstract. Chapter 8 Interfaces and Nested Classes
Using Multiple Interfaces continued public class SpinningTopimplements Rotatable, Whistler { private intrevolutionsPerMinute = 100; public double angularSpeed() { double speed = (revolutionsPerMinute * 2 * Math.PI)/SECONDS_PER_MINUTE; return speed; } public void rotate(double angularSpeed) { System.out.println("Rotating with angular speed " +angularSpeed); } public void whistle() { System.out.println("Whistling"); } } • Class SpinningTop implements both Rotatable and Whistler interfaces: Chapter 8 Interfaces and Nested Classes
An Interface as a Data Type • The name of an interface also represents a data type. • Because ColorMixable is an interface, we can declare variable cm as: ColorMixable cm; • This variable cm can be assigned to an instance of any class that implements this interface: cm = new ColoredEllipse(10, 10, 50, 70); Chapter 8 Interfaces and Nested Classes
Casting Interface Types public interface Bounce { void bounce(); } public interface Roll { void roll(); } • Two interfaces Bounce and Roll: • Class Ball implements interfaces Bounce and Roll. • Variable r of type Roll can be assigned to an instance of Ball: Roll r = new Ball(); • Calls the roll method of the Ball class: r.roll(); Chapter 8 Interfaces and Nested Classes
Casting Interface Types continued • These two statements cause a compilation error (Why?): r.bounce(); // error r.inflate(); // error • Solution is to cast the reference variable r to type Ball: (Ball) r • Call the bounce and inflate methods in Ball as follows: ((Ball) r).bounce(); // okay ((Ball) r).inflate(); // okay Chapter 8 Interfaces and Nested Classes
Exercise • What is the problem with the following cast? (Ball) r.bounce(); • Solution: This will cast the value returned by the method bounce (and not the reference variable r) to type Ball. Chapter 8 Interfaces and Nested Classes
The instanceOf Keyword public class Dice implements Roll { public void roll() { System.out.println("Rolling dice"); } } • Casting incorrectly can lead to runtime error. • Example: • Class Dice implements the Roll interface: • Can assign variable dice of type Roll to an instance of Dice: Roll dice = new Dice(); • Cannot cast dice to type Ball because the classes Ball and Dice are unrelated: Ball b = (Ball) dice; // error! ((Ball) dice).roll(); // error! Chapter 8 Interfaces and Nested Classes
The instanceOf Keyword continued • A reference variable ref should be cast to type T only if: • ref references an instance of class T, or • ref references an instance of a class that implements the interface T. • Keyword instanceof can be used to determine if an object is of a given type. • This statement returns true if object obj is of type T; otherwise, it returns false: if(objinstanceof T) Chapter 8 Interfaces and Nested Classes
The instanceOf Keyword continued if(dice instanceof Ball) ((Ball) dice).roll(); • Example: • A runtime error does not occur if dice does not reference an instance of Ball: Chapter 8 Interfaces and Nested Classes
Extending an Interface public interface J extends I { // new abstract methods and constants } // J, K and L are interfaces public interface M extends J, K, L { // new abstract methods and constants } Interfaces are extended using the extend keyword: I is called the superinterface of J, and J is the subinterface of I. J inherits all the abstract methods and constants of I. Multiple inheritance is allowed: Chapter 8 Interfaces and Nested Classes
Pre-defined Interfaces The Shape Interface The Collection Interface The EventListener Interface The Runnable Interface Chapter 8 Interfaces and Nested Classes
The Shape Interface public abstract void draw(Shape s) public abstract void fill(Shape s) • A Java 2D interface. • Classes Rectangle2D.Float, Rectangle2D.Double, Line2D.Float, Line2D.Double and Polygon implement this interface. • Therefore, all instances of these classes are also of type Shape. • The draw and fill methods of Graphics2D class are defined as follows: Can pass instances of classes that implement Shape as arguments to these methods. Chapter 8 Interfaces and Nested Classes
The Collection Interface • Declares methods to manipulate a group of objects. • The Set, List and Queue interfaces extend Collection: • A Set is a collection with the property that duplicate objects cannot be present. • The List is a collection where objects are placed at a certain position or index, and duplicates are allowed. • Objects also have a given order in a Queue, but the ordering scheme is different from that in List. • These interfaces are a part of the Java Collections Framework. Chapter 8 Interfaces and Nested Classes
The EventListener Interface Behavior of objects when events such clicking a mouse, pressing a key on the keyboard or closing a window on the screen occur. Does not have any methods or constants. Extended by interfaces WindowListener, MouseListener and KeyListener, which reside in the java.awt.package. Chapter 8 Interfaces and Nested Classes
The MouseListener Interface public interface MouseListener extends EventListener { public abstract void mouseClicked(MouseEvent e); public abstract void mousePressed(MouseEvent e); public abstract void mouseReleased(MouseEvent e); public abstract void mouseEntered(MouseEvent e); public abstract void mouseExited(MouseEvent e); } The MouseListener interface declares methods that are invoked when the mouse is pressed, released or moved: Chapter 8 Interfaces and Nested Classes
The MouseListener Interface continued Any class that implements MouseListener must implement all the methods in this interface. An instance of this class is automatically notified whenever a mouse action occurs (such as when the user clicks, presses, or releases a mouse button) via a MouseEvent object. The MouseEvent class contains methods to obtain information about a mouse action. Chapter 8 Interfaces and Nested Classes
The WindowListener and KeyListener Interfaces The WindowListener interface declares methods that are invoked when a window is opened, closed or changed. The KeyListener interface defines methods that are invoked when a key is pressed or released on the keyboard. Chapter 8 Interfaces and Nested Classes
The Runnable Interface public interface Runnable { public abstract void run(); } Defined in the java.lang package: Any class that implements this interface must provide the implementation for the method run. This method is used as the body of threads in a multithreaded program, which consists of many threads executing code in parallel. Chapter 8 Interfaces and Nested Classes
Nested Interfaces public class Bulb { public static interface Glow { } } • A nested interface is an interface defined within another class. • Should be declared using the static modifier since it is associated with the class itself and not the instances of the class. • Example: • The class Bulb contains a nested interface called Glow: • A private nested interface can be used only within its enclosing class; however, a public nested interface can be accessed outside the class in which it is defined. Chapter 8 Interfaces and Nested Classes
Nested Classes public class Bulb { public static interface Glow { } public class Filament implements Glow { } } • A nested class is a class defined within another class. • Example: • Class Filament is a nested class: • Nested interfaces and nested classes can be declared using any access modifier. • Nested classes can be made abstract or final. Chapter 8 Interfaces and Nested Classes
Nested Classes continued • Two types: • Static nested classes • Static members of the enclosing class • Non-static nested classes (also known as inner classes) • Non-static members of the enclosing class Chapter 8 Interfaces and Nested Classes
Static Nested Classes public class TopLevel { // code for Top Level private static class StaticNested { // code for class StaticNested } } Declared within another class using the static modifier. All instances of a top-level class share a single instance of a static nested class. A static nested class can access even the privatestatic fields of its top-level class. Example: Chapter 8 Interfaces and Nested Classes
Example of a Static Nested Class public class Ticket { private int number; private static int count; // assign a new number to this ticket Ticket() { number = Counter.getNextNumber(); } // Counter is a static nested class private static class Counter { // increments count private static int getNextNumber() { count++; return count; } } // accessor method getNumber for field number } Chapter 8 Interfaces and Nested Classes
Static Nested Classes continued • A static nested class is created automatically using the default constructor when an instance of its enclosing class is created. • The following statement creates an instance of Counter as well: Ticket t1 = new Ticket(); • Ticket objects that are created subsequently share this Counter object: Ticket t2 = new Ticket(); Chapter 8 Interfaces and Nested Classes
Exercise public static void main(String[] args) { Ticket t1 = new Ticket(); System.out.println("Ticket t1 has id: " +t1.getNumber()); Ticket t2 = new Ticket(); System.out.println("Ticket t2 has id: " +t2.getNumber()); } • Add this main to class Ticket and compile and run the program. What is the output? Chapter 8 Interfaces and Nested Classes
Public Static Nested Classes public abstract class Rectangle2D { // fields and methods in Rectangle2D public static class Float extends Rectangle2D { // fields and methods of Float } public static class Double extends Rectangle2D { // fields and methods of Double } } • Java 2D defines Float and Double as public nested classes inside class Rectangle2D: • Referenced as Rectangle2D.Float and Rectangle2D.Double. • When should a nested class be declared as public? As private? Chapter 8 Interfaces and Nested Classes
Inner Classes public class Camera { private class CameraBody { // fields and methods of inner class } } • Defined inside another class and declared without using the static modifier. • Declare a class as an inner class when it will be used only within another class and its code is short. • Example: • Camera contains an inner class called CameraBody: Chapter 8 Interfaces and Nested Classes
Inner Classes continued Every instance of the enclosing class contains a separate instance of the inner class. Unlike top-level classes, an inner class can be declared using any of the access modifiers. All fields and methods of the inner class can be accessed by the enclosing class, and vice-versa. An inner class cannot contain static fields, static methods, and interfaces, but can contain constants. Chapter 8 Interfaces and Nested Classes
Exercise public class Outside { private class Inside { public static final inti = 10; public interface i { } public static int x; public static intsetX() { } } } Which declarations in class Outside are incorrect? Chapter 8 Interfaces and Nested Classes
Palette: Class Palette What is the advantage of declaring mixingArea as ColorMixable? public class Palette { // mixing area private ColorMixablemixingArea; // colored ellipses represent paint swatches private ColorButton red, blue, yellow, green; public Palette(ColorMixable cm) { // code to instantiate red, blue, yellow, and green mixingArea = cm; } // code for inner class ColorButton (see next slide) private void changeColor(Color newColor) { mixingArea.mixColor(newColor); } } Chapter 8 Interfaces and Nested Classes
Palette: Class Palette continued private class ColorButton extends Ellipse2D.Float { private Color color; privateColorButton(Color c1, float x, float y, float w, float h) { super(x, y, w, h); color = c1; } private Color getColor() { return color; } } Inner class ColorButton in class Palette: Chapter 8 Interfaces and Nested Classes
Palette: Class Palette continued private class ColorButton extends Ellipse2D.Floatimplements MouseListener { // checks whether the mouse was clicked inside this object // and updates the color of mixingArea public void mouseClicked(MouseEvent e) { // code get the coordinates of the point // where mouse is clicked // code to check if this object was clicked // update the color of mixingArea accordingly } // no action is taken for other types of mouse motion public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} } • Modified class ColorButton implements interface MouseListener (only the new code added is shown here): Chapter 8 Interfaces and Nested Classes
Anonymous Classes • An anonymous class is an inner class without a name, defined inside a method or constructor. • An anonymous class is created by • extending an existing class OR • implementing an existing interface. • Only the default access modifier can be used to declare an anonymous class. Chapter 8 Interfaces and Nested Classes
Creating an Anonymous Class by Extending an Existing Class The keyword extends is not needed to create an anonymous class. This anonymous class implicitly inherits from the super class. In addition, an instance of this class is also created at the same time by using the new keyword. Chapter 8 Interfaces and Nested Classes