1 / 46

Interface and Inner classes

Interface and Inner classes. Jiafan Zhou. Better Control. Interfaces and inner classes provide more sophisticated ways to organize and control the objects in your system. C++, for example, does not contain such mechanisms.

mariko
Download Presentation

Interface and Inner classes

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. Interface and Inner classes Jiafan Zhou

  2. Better Control • Interfaces and inner classes provide more sophisticated ways to organize and control the objects in your system. • C++, for example, does not contain such mechanisms. • The interface keyword produces a completely abstract class, one that provides no implementation at all.

  3. Interfaces • The interface keyword takes the abstract concept one step further: a “pure” abstract class. • To establish the form for a class: method names, argument lists, and return types, but no method bodies. Interface methods are implicitly public abstract and non-static. • An interface can also contain fields, but these are implicitly public and static and final. • An interface provides only a form, but no implementation. Interface is more abstract than abstract class.

  4. Used as a Contract • An interface says, “This is what all classes that implement this particular interface will look like.” • A code that uses a particular interface knows what methods might be called for that interface. • So the interface is used to establish a “protocol” between classes.

  5. Create an Interface • Use interface as keyword rather than class. public interface MyInterface { //… } • Public or Package Access level control only like class • To make a class that conforms to a particular interface, use the implements keyword.public class MyClass implements MyInterface { //… } • To make an interface inherits another interface, use the extends keyword.public interface MyInterface extends MyInterface { //… }

  6. Instrument Example Methods in Interface are automatically public and abstract. Implementing class must declare the method as public.

  7. class Brass extends Wind { public void play(Note n) { System.out.println("Brass.play() " + n); } public void adjust() { System.out.println("Brass.adjust()"); } } class Woodwind extends Wind { public void play(Note n) { System.out.println("Woodwind.play() " + n); } public String what() { return "Woodwind"; } } interface Instrument { // Compile-time constant: int I = 5; // static & final // Cannot have method definitions: void play(Note n); // Automatically public String what(); void adjust(); } class Wind implements Instrument { public void play(Note n) { System.out.println("Wind.play() " + n); } public String what() { return "Wind"; } public void adjust() {} } class Percussion implements Instrument { public void play(Note n) { System.out.println("Percussion.play() " + n); } public String what() { return "Percussion"; } public void adjust() {} } class Stringed implements Instrument { public void play(Note n) { System.out.println("Stringed.play() " + n); } public String what() { return "Stringed"; } public void adjust() {} }

  8. public class Music5 { // Doesn't care about type, so new types // added to the system still work right: static void tune(Instrument i) { i.play(Note.MIDDLE_C); } static void tuneAll(Instrument[] e) { for(int i = 0; i < e.length; i++) tune(e[i]); } public static void main(String[] args) { // Upcasting during addition to the array: Instrument[] orchestra = { new Wind(), new Percussion(), new Stringed(), new Brass(), new Woodwind() }; tuneAll(orchestra); } } "Wind.play() Middle C", "Percussion.play() Middle C", "Stringed.play() Middle C", "Brass.play() Middle C", "Woodwind.play() Middle C" It doesn’t matter if you are upcasting to a “regular” class called Instrument, an abstract class called Instrument, or to an interface called Instrument. The behavior is the same. In fact, you can see in the tune( ) method that there isn’t any evidence about whether Instrument is a “regular” class, an abstract class, or an interface.

  9. “Multiple inheritance” in Java • The interface isn’t simply a “more pure” form of abstract class. • It has a higher purpose than that. – “Multiple Inheritance”. • When you need to say “An x is an a and a b and a c.” • In C++, this act of combining multiple class interfaces is called multiple inheritance. • In Java, you can perform the same act, but only one of the classes can have an implementation, rest of them are multiple interfaces:

  10. “Multiple inheritance” in Java • A class can implement any number of interfaces, but it can extends only one class.public class MySubClass extends MySuperClass implements MyInterface1, MyInterface2, MyInterface3 {} • An interface can extend any number of interfaces, but it cannot implement another interface. • Class to class inheritance => use extends • Interface to interface inheritance => use extends • Class to interface inheritance => use implements

  11. If you do inherit from a non-interface, you can inherit from only one. You place all the interface names after the implements keyword and separate them with commas. You can have as many interfaces as you want; each one becomes an independent type that you can upcast to. All the rest of the base elements must be interfaces.

  12. interface CanFight { void fight(); } interface CanSwim { void swim(); } interface CanFly { void fly(); } class ActionCharacter { public void fight() {} } class Hero extends ActionCharacter implements CanFight, CanSwim, CanFly { public void swim() {} public void fly() {} // fight() function is defined in base class } public class Adventure { public static void t(CanFight x) { x.fight(); } public static void u(CanSwim x) { x.swim(); } public static void v(CanFly x) { x.fly(); } public static void w(ActionCharacter x) { x.fight(); } public static void main(String[] args) { Hero h = new Hero(); t(h); // Treat it as a CanFight u(h); // Treat it as a CanSwim v(h); // Treat it as a CanFly w(h); // Treat it as an ActionCharacter } }

  13. Name collisions when combining interfaces interface I1 { void f(); } interface I2 { int f(int i); } interface I3 { int f(); } class C { public int f() { return 1; } } class C2 extends C implements I1, I2 { public void f() {} public int f(int i) { return 1; } // overloaded } class C3 extends C implements I2 { public int f(int i) { return 1; } // overloaded } class C4 extends C implements I3 { // Identical, no problem: public int f() { return 1; } } // Methods differ only by return type: //! class C5 extends C implements I1 {} //! interface I4 extends I1, I3 {} If you try to create class C5, compiler will complain.

  14. Extending an interface 
with inheritance • You can easily add new method declarations to an interface by using inheritance. • You can also combine several interfaces into a new interface with inheritance. • In both cases you get a new interface.

  15. interface Monster { void menace(); } interface DangerousMonster extends Monster { void destroy(); } interface Lethal { void kill(); } class DragonZilla implements DangerousMonster { public void menace() {} public void destroy() {} } interface Vampire extends DangerousMonster, Lethal { void drinkBlood(); } class VeryBadVampire implements Vampire { public void menace() {} public void destroy() {} public void kill() {} public void drinkBlood() {} } public class HorrorShow { static void u(Monster b) { b.menace(); } static void v(DangerousMonster d) { d.menace(); d.destroy(); } static void w(Lethal l) { l.kill(); } public static void main(String[] args) { DangerousMonster barney = new DragonZilla(); u(barney); v(barney); Vampire vlad = new VeryBadVampire(); u(vlad); v(vlad); w(vlad); } }

  16. Grouping constants • Any fields you put into an interface are automatically public, static and final. • In the old days Interface is a convenient tool for creating groups of constant values • Now, we use enums to group constants from JDK6.0 public interface Months { int JANUARY = 1, FEBRUARY = 2, MARCH = 3, APRIL = 4, MAY = 5, JUNE = 6, JULY = 7, AUGUST = 8, SEPTEMBER = 9, OCTOBER = 10, NOVEMBER = 11, DECEMBER = 12; } //… Months.JANUARY;

  17. Initializing fields in interfaces • Fields defined in interfaces are automatically static and final. • They can be initialized with nonconstant expressions public interface RandVals { Random rand = new Random(); int randomInt = rand.nextInt(10); long randomLong = rand.nextLong() * 10; float randomFloat = rand.nextLong() * 10; double randomDouble = rand.nextDouble() * 10; }

  18. Methods Return Interface • A method that declares a class as a return type can return any object which is of the subclass type. • A method that declares an interface as a return type can return any object whose class implements that interface. public interface Interface1 { Object getMeObject(); Interface1 getMeInterface(); } public class MyClass implements Interface1 { public String getMeObject() {} public MyClass getMeInterface(){} }

  19. UML diagram of Object Model

  20. instanceof keyword • The instanceof operator is a keyword in Java and it is used for object reference variables only. It is used to check if an object is of a particular type. • Animal h1 = new Human(); • System.out.println(h1 instanceof Object);System.out.println(h1 instanceof Animal);System.out.println(h1 instanceof Mammal);System.out.println(h1 instanceof Human); • System.out.println(h1 instanceof Cat);System.out.println(h1 instanceof Dog);

  21. Inner classes • To place a class definition within another class definition is called inner class. • Group classes that logically belong together and to control the visibility of one within the other. • Inner classes are distinctly different from composition.

  22. public class Parcel1 { class Contents { private int i = 11; public int value() { return i; } } class Destination { private String label; Destination(String whereTo) { label = whereTo; } String readLabel() { return label; } } // Using inner classes looks just like // using any other class, within Parcel1: public void ship(String dest) { Contents c = new Contents(); Destination d = new Destination(dest); System.out.println(d.readLabel()); } public static void main(String[] args) { Parcel1 p = new Parcel1(); p.ship("Tanzania"); } } The inner classes, when used inside ship( ), look just like the use of any other classes. The only practical difference is that the names are nested within Parcel1. More typically, an outer class will have a method that returns a reference to an inner class. See the next example.

  23. public class Parcel2 { class Contents { private int i = 11; public int value() { return i; } } class Destination { private String label; Destination(String whereTo) { label = whereTo; } String readLabel() { return label; } } public Destination to(String s) { return new Destination(s); } public Contents cont() { return new Contents(); } public void ship(String dest) { Contents c = cont(); Destination d = to(dest); System.out.println(d.readLabel()); } public static void main(String[] args) { Parcel2 p = new Parcel2(); p.ship("Tanzania"); Parcel2 q = new Parcel2(); // Defining references to inner classes: Parcel2.Contents c = q.cont(); Parcel2.Destination d = q.to("Borneo"); } } If you want to make an object of the inner class anywhere except from within a non-static method of the outer class, you must specify the type of that object as OuterClassName.InnerClassName To instantiate a non-static inner class, you need an instance of the outer class first. Parcel2.Contents c = q.cont(); // where q is the instance of the outer class Parcel2

  24. Non-static inner class Instantiation • A non-static inner class has access to all the members of the outer class. From inside the outer instance code, use the inner class name alone to instantiate it. public class MyClass { MyInner myInner = new MyInner(); public class MyInner {} } • From outside the outer instance code, the inner class name must be included in the outer instance: class AnotherClass { MyClass.MyInner inner = new MyClass().new MyInner(); }

  25. Static inner class Instantiation • Static inner class behaves like static members. public class OuterClass{ InnerClass myInner = new InnerClass(); public void outClassMethod(){ System.out.println(InnerClass.index); System.out.println(myInner.index); } static public class InnerClass{ public static int index = 10; } } class AnotherClass{ int index = 0; // this is a non-static initialisation block { this.index = OuterClass.InnerClass.index; } }

  26. Inner classes and upcasting • Inner classes are more powerful when you start upcasting to a base class, and in particular to an interface. • The inner class—the implementation of the interface—can then be completely unseen and unavailable to anyone, which is convenient for hiding the implementation. • All you get back is a reference to the base class or the interface.

  27. The common interfaces will be declared in their own files: public interface Destination { String readLabel(); } public interface Contents { int value(); } Now Contents and Destination represent interfaces available to the client programmer.

  28. class Parcel3 { private class PContents implements Contents { private int i = 11; public int value() { return i; } } protected class PDestination implements Destination { private String label; private PDestination(String whereTo) { label = whereTo; } public String readLabel() { return label; } } public Destination dest(String s) { return new PDestination(s); } public Contents cont() { return new PContents(); } } public class TestParcel { public static void main(String[] args) { Parcel3 p = new Parcel3(); Contents c = p.cont(); Destination d = p.dest("Tanzania"); // Illegal -- can't access private class: //! Parcel3.PContents pc = p.new PContents(); } } PContents is private, so no one but Parcel3 can access it Normal (non-inner) classes cannot be made private or protected; they may only be given public or package access

  29. Inner classes in methods and scopes • Two reasons why we need inner classes: • As shown previously, you’re implementing an interface of some kind so that you can create and return a reference. • You’re solving a complicated problem and you want to create a class to aid in your solution, but you don’t want it publicly available.

  30. Reaching outward from a multiply-nested class • It doesn’t matter how deeply an inner class may be nested—it can transparently access all of the members of all the classes it is nested within class MNA { private void f() {} class A { private void g() {} public class B { void h() { g(); f(); } } } } public class MultiNestingAccess { public static void main(String[] args) { MNA mna = new MNA(); MNA.A mnaa = mna.new A(); MNA.A.B mnaab = mnaa.new B(); mnaab.h(); } }

  31. My tips on Inner classes • Inner classes (static or non-static) can be completed replaced by using “standard” outer classes only. • In the real world programming when engineering an object mode, you should not tend to use the inner classes. Refer to the Animal object model for reference. • Good news, you may not see a lot inner classes in the real world. Only in the SCJP exams. • Finally, one more heavy concept: Anonymous inner classes. The most difficult concept in SCJP.

  32. Anonymous inner classes class MyContents implements Contents { private int i = 11; public int value() { return i; } } return new MyContents(); public class Parcel6 { public Contents cont() { return new Contents() { private int i = 11; public int value() { return i; } }; // Semicolon required in this case } public static void main(String[] args) { Parcel6 p = new Parcel6(); Contents c = p.cont(); } } The cont( ) method combines the creation of the return value with the definition of the class that represents that return value The class is anonymous; it has no name. “Create an object of an anonymous class that’s inherited from Contents.”

  33. Hands on anonymous inner classes • Anonymous inner classes are especially prone to errors • Usually you identify a semicolon at the end of the anonymous inner class defined inside a method argument • Watch me writing some examples of anonymous inner class • Examples in the mock examples.

  34. Homework

  35. Homework • Update your banking system with some interfaces and inner classes. • Create at least two common interfaces for your design. • Create at least two inner classes in your design. • Make sure you understand the anonymous inner classes • Try to utilise anonymous inner classes

  36. Questions & Answers

  37. Mock Exam Questions: Question 1: Given: 11. public interface Status { 12. /* insert code here */ int MY_VALUE = 10; 13. } Which three are valid on line 12? (Choose three.) A. final B. static C. native D. public E. private F. abstract G. protected 37

  38. Mock Exam Questions: Question 15 Given: 10. interface Foo { int bar(); } 11. public class Sprite { 12. public int fubar( Foo foo) { return foo.bar(); } 13. public void testFoo() { 14. fubar( 15. // insert code here 16.); 17. } 18. } Which code, inserted at line 15, allows the class Sprite to compile? A. Foo { public int bar() { return 1; } } B. new Foo { public int bar() { return 1; } } C. new Foo() { public int bar(){return 1; } } D. new class Foo { public int bar() { return 1; } } 38

  39. Mock Exam Questions: Question 16 Click the Exhibit button. 10. interface Foo { 11. int bar(); 12. } 13. 14. public class Beta { 15. 16. class A implements Foo { 17. public int bar() { return 1; } 18. } 19. 20. public int fubar( Foo foo) { return foo.bar(); } 21. 22. public void testFoo() { 23. 24. class A implements Foo { 25. public int bar() { return 2; } 26. } 27. 28. System.out.println( fubar( new A())); 29. } 30. 31. public static void main( String[] argv) { 32. new Beta().testFoo(); 33. } 34. } Which three statements are true? (Choose three.) A. Compilation fails. B. The code compiles and the output is 2. C. If lines 16, 17 and 18 were removed, compilation would fail. D. If lines 24, 25 and 26 were removed, compilation would fail. E. If lines 16, 17 and 18 were removed, the code would compile and the output would be 2. F. If lines 24, 25 and 26 were removed, the code would compile and the output would be 1. 39

  40. Mock Exam Questions: Question 20 Given: 1. interface TestA { String toString(); } 2. public class Test { 3. public static void main(String[] args) { 4. System.out.println(new TestA() { 5. public String toString() { return “test”; } 6. }); 7. } 8. } What is the result? A. test B. null C. An exception is thrown at runtime. D. Compilation fails because of an error in line 1. E. Compilation fails because of an error in line 4. F. Compilation fails because of an error in line 5. 40

  41. Mock Exam Questions: Question 23 Given: 10. interface Data { public void load(); } 11. abstract class Info { public abstract void load(); } Which class correctly uses the Data interface and Info class? A. public class Employee extends Info implements Data { public void load() { /*do something*/ } } B. public class Employee implements Info extends Data { public void load() { /*do something*/ } } C. public class Employee extends Info implements Data { public void load() { /*do something */ } public void Info.load() { /*do something*/ } } D. public class Employee implements Info extends Data { public void Data.load() { /*d something */ } public void load() { /*do something */ } } E. public class Employee implements Info extends Data { public void load() { /*do something */ } public void Info.load(){ /*do something*/ } } F. public class Employee extends Info implements Data{ public void Data.load() { /*do something*/ } public void Info.load() { /*do something*/ } 41

  42. Mock Exam Questions: Which two classes use the Shape class correctly? (Choose two.) A. public class Circle implements Shape { private int radius; } B. public abstract class Circle extends Shape { private int radius; } C. public class Circle extends Shape { private int radius; public void draw(); } D. public abstract class Circle implements Shape { private int radius; public void draw(); } E. public class Circle extends Shape { private int radius; public void draw() {/* code here */} } F. public abstract class Circle implements Shape { private int radius; public void draw() { / code here */ } } Question 24 Given: 11. public abstract class Shape { 12. private int x; 13. private int y; 14. public abstract void draw(); 15. public void setAnchor(int x, int y) { 16. this.x = x; 17. this.y = y; 18. } 19. } 42

  43. Mock Exam Questions: Question 25 Which two classes correctly implement both the java.lang.Runnable and the java.lang.Clonable interfaces? (Choose two.) A. public class Session implements Runnable, Clonable { public void run(); public Object clone(); } B. public class Session extends Runnable, Clonable { public void run() { / do something */ } public Object clone() { / make a copy */ } } C. public class Session implements Runnable, Clonable { public void run() { / do something */ } public Object clone() { /* make a copy */ } } D. public abstract class Session implements Runnable, Clonable { public void run() { / do something */ } public Object clone() { /*make a copy */ } } E. public class Session implements Runnable, implements Clonable { public void run() { / do something */ } public Object clone() { / make a copy */ } } 43

  44. Mock Exam Questions: Question26 Click the Exhibit button. 1. public class GoTest { 2. public static void main(String[] args) { 3. Sente a = new Sente(); a.go(); 4. Goban b = new Goban(); b.go(); 5. Stone c = new Stone(); c.go(); 6. } 7. } 8. 9. class Sente implements Go { 10. public void go() { System.out.println(”go in Sente.”); } 11. } 12. 13. class Goban extends Sente { 14. public void go() { System.out.println(”go in Goban”); } 15. } 16. 17. class Stone extends Goban implements Go { } 18. 19. interface Go { public void go(); } What is the result? A. go in Goban go in Sente go in Sente B. go in Sente go in Sente go in Goban C. go in Sente go in Goban go in Goban D. go in Goban go in Goban go in Sente E. Compilation fails because of an error in line 17. 44

  45. Mock Exam Questions: Question 46 46. Given: 10. class Line { 11. public static class Point { } 12. } 13. 14. class Triangle { 15. // insert code here 16. } Which code, inserted at line 15, creates an instance of the Point class defined in Line? A. Point p = new Point(); B. Line.Point p = new Line.Point(); C. The Point class cannot be instatiated at line 15. D. Line 1 = new Line() ; 1.Point p = new 1.Point(); 45

  46. Mock Exam Questions: Question 47 Given: 10. class Line { 11. public class Point { public int x,y; } 12. public Point getPoint() { return new Point(); } 13. } 14. class Triangle { 15. public Triangle() { 16. // insert code here 17. } 18. } Which code, inserted at line 16, correctly retrieves a local instance of a Point object? A. Point p = Line.getPoint(); B. Line.Point p = Line.getPoint(); C. Point p = (new Line()).getPoint(); D. Line.Point p = (new Line()).getPoint(); 46

More Related