1 / 50

Interfaces 、 Packages and Inner class

Lecture6. Interfaces 、 Packages and Inner class. Objectives. Interface & multiple inheritance Declaration 、 implement 、 extends Interface vs. abstract class Package Statement 、 import Access Protection Inner Class. Interfaces. What are Interfaces

fleta
Télécharger la présentation

Interfaces 、 Packages and Inner class

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. Lecture6 Interfaces、Packagesand Inner class

  2. Objectives • Interface & multiple inheritance • Declaration、implement、extends • Interface vs. abstract class • Package • Statement、import • Access Protection • Inner Class

  3. Interfaces • What are Interfaces • An interface is a type, which is only made up of abstract methods and constants • Declaration • [public] interface <name> [extends <superinterface name>] {[<return-type><method-name>(<parameter-list>);]* • [<type> <final-var> = <value>; ]*} // []* -- 0 or many times • Methods: abstract, public, native • Variables: public, static, final (constants) • There are no constructors in interfaces • Interface types may be used to declare variables

  4. Example interface Attributed { void add(Attr newAttr); // add an attibute Attr find(String attrName); // find an attibute by name Attr remove(String attrName); //find an attibute by name java.util.Enumeration attrs(); // return the current attrs } // java.util.Enumeration is also an interface interface Verbose { int SILENT = 0; int TERSE=1; int NORMAL=2; int VERBOSE=3; void setVerbosity(int level); int getVerbosity(); }

  5. Function • By interfaces, we can • Extract same behaviors from unrelated classes • Specify the methods need to be implemented by many classes • Understand the interactive interfaces of objects, instead of the classes of objects

  6. Implement • An interface is actually meaningful only when it has been implemented by a class • class <classname> [extends <superclass>] • [implements <interface-list>] { <class_body> } interface Callback { void callback(int param); } class Client implements Callback { public void callback(int p){ System.out.println(“called with”+p); } } … Callback c = new Client(); c.callback(42); // c cann’t access other methods of Client

  7. Notes • The methods for implementing an interface must be public • The methods(implement an interface) must have the same signatures as the abstract methods in the interface • A class mayimplementseveral interfaces • An interface may be implemented by many classes • The interface variables are used as constants in the classes implementing the interface(just as #define in C) • If a class implements an interfaces, but has not implemented all the interface methods, it must be abstract

  8. Example(1) import java.util.Random; interface S { int NO = 0; int YES = 1; int NEVER = 3; } Class A implements S { static void a(int result) { switch(result) { case NO: ….; break; case YES: …; break; case NEVER: …; break; } } … Q q = new Q(); a(q.ask()); a(q.ask()); …} class Q implements S { Randoam rand = new Random(); int ask() { int prob=(int) (100*rand.nextDouble()); if (prob < 30) return NO; else if (prob<70) return YES; else return NEVER;} }

  9. Example(2) import java.util.*; Class AttributedImpl implements Attributed { protected Hashtable attrTable = new Hashtable(); public void add(Attr newAttr) { attrTable.put(newAttr.name(), newAttr); } public Attr find(String name) { return (Attr)attrTable.get(name); } public Attr remove(String name) { return (Attr)attrTable.remove(name); } public Enumeration attrs() { return attrTable.elements(); } }

  10. Interface Inheritance(1) • Multiple Inheritance • More than one direct superclass • Conflict: X(m),Y(m)—Z(m?) • Solution: inherit specification, not implementation • Interface and Specification • Supertype/subtype • (2) Interface Inheritance • interface <name> extends <interface-name-list> { • [<return-type><method-name>(<parameter-list>); ]* • [<type> <final-var> = <value>; ]* • }

  11. W Interface Inheritance(2) X Y Z • The new interface is made up of all the abstract methods and constants of the inherited interfaces, together with the defined methods and constants • Multiple inheritance: an interface may extend several interfaces • Though there is no root interface, an expression of interface type can be assigned to an Object variable • protected void twiddle(W wRef) { // right • Object obj = wRef; // … } • Example : interface W { } interface X extends W { } interface Y extends W{ } class Z implements X,Y { } interface W { } interface X extends W { } class Y implements W { } class Z extends Y implements X { }

  12. Conflict Resolution(1) • An interface(Z) may be a subtype of more than one interfaces (X,Y). What will happen when a method name(M) or a constant (C) is contained in all these interfaces(X,Y)? • If the signature of M in X is the same as that in Y, Z will have one method of such signature • If the numbers or the types of M parameters in X and Y are different, Z will have two overloading M methods • If M in X and M in Y are only different in return types, the two interfaces can not be implemented simultaneously • If M in X and M in Y are only different in exception types, there must be a unique implementation which will deal with the two exception types simultaneously

  13. Conflict Resolution(2) interface X { void setup() throws SomeException; } interface Y { void setup(); } class Z implements X,Y { public void setup() { //meets both X.setup and Y.setup //… it can have fewer exception types than supers } // impossible if X.setup and Y.setup have different } // meanings or incompatible exception types • Combine X and Y into a hierarchy when X.C != Y.C and Z can implement both X and Y, and access C by X.C and Y.C in Z and Z’s subtypes

  14. Interfaces and Classes • Interfaces and Classes • Multiple inheritance vs. single inheritance • Abstract classes may contain method implementations, protected members, static methods, whereas interfaces have only public methods and constants • Both are basic components of Java programs • A class may implement several interfaces • An interface may be implemented by several classes • A variable declared as an interface type may reference to an object of any class which implements the interface. Thus, same methods from different classes may be invoked. (Interfaces are designed to support dynamic method call)

  15. Interfaces, Classes and Types • A type implies a set of values(objects) and a set of operations(object methods) • Class type. The value set: all instances of the class and its subclasses. The operation set: all methods in the class • Interface type. The value set: all instances of all the classes implement the interface and their subclasses. The operation set: all methods defined in the interface • If a class implements an interface, the objects of the class and its subclasses can be referenced by either the class type or the interface type(polymorphism)

  16. Packages • Why • Need a mechanism for name space management, because of the problem of name space of identifiers and reuse • Group related classes and interfaces • Control member access(container) • Java Package • Package: how to scope class, interface, method, variable • Import: how to use other classes and packages

  17. The Package Statement • package pkg1[.pkg2[.pkg3]]; • Tell the compiler which package the class belongs to • The class belongs to an unnamed package if there is no package statement • Java compiler stores packages by file(directory) system, so that packages have a tree-like structure • If the Pkg package is declared, the source file of the class must be stored in the Pkg directory. Directory name and package name must be the same(case-sensitive) • Example: package java.awt.image • java/awt/image(unix), java\awt\image(Win95), ect • Complile class: use full package path, or put package path into CLASSPATH( such as “.; \java\classes; <progdir>”)

  18. Example(1) package p1; Public class Protection { …} package p2; public class Derived2 extends p1.Protection{…} E:\javafile>md p1 E:\javafile\p1>edit (Protection.java) E:\javafile>md p2 E:\javafile\p2>edit (Derived2.java) E:\> Set classpath=e:\jdk\lib\classes.zip;e:\javafile; E:\> e:\jdk\bin\javac e:\javafile\p1\Protection.java E:\>e:\jdk\bin\java p1.Protection

  19. Example(2) //file name:ABC.java package test; public class ABC { …} //file name:PackageTest.java import test.*; class PackageTest { …} CLASSPATH = c:\jdk\lib\classes.zip; c:\class • While compiling PackageTest.java, Compiler will search in these ways • test\ASC.class inside c:\jdk\lib\classes.zip • c:\class\test\ABC.class • .\test\ABC.class • java.language(at last)

  20. The import Statement • Why • All built-in classes are grouped into the (java) packages • Using the full package path in programs is not a good way • ‘imported’ makes classes and packages accessed directly • Syntax import pkg1[.pkg2].(<classname>|*); • Example • import java.util.Date; import java.io.*; • Notes • The classes and packages that will be used in a program must be imported • A program using ‘*’ will be compiled more slowly. But ‘*’ does not affect the performance and size of the class

  21. Access Protection • Purpose • Control the visibility(scope) of data and methods • Mechanisms • Class: container of variables and methods. A variable or method of a class is open to the other members in the class • Package: container of classes, interfaces and other pkgs • Modifiers: private, public, protected,package(friendly) • Relationships of Two Classes • R1: a subclass in the same package • R2: a non-subclass in the same package • R3: a subclass in a different package. • R4: a non-subclass in a different package

  22. Example(1) package p1; Public class Protection { int n =1; private int npri = 2; protected int npro = 3; public int npub=4; public Protection() { System.out.println(“base constructor”); System.out.println(“n = ” + n); System.out.println(“npri =” + npri); System.out.println(“npro =” + npro); System.out.println(“npub =” + npub); } private void f1() { System.out.println(“f1-” + npri); }

  23. Example(2) Protected void f2() { System.out.println(“f2-” + npro); } Public void f3() { System.out.println(“f3-” + npub); } void f4() { System.out.println(“f4-” + n); } Public static void main(String args[]) { Protection pp = new Protection(); System.out.println(“pp”); pp.f1(); pp.f2(); pp.f3(); pp.f4() } } base constructor n=1 npri=2 npro=3 npub=4 pp f1-2 f2-3 f3-4 f4-1

  24. Example(3) package p1; public class Derived extends Protection { public Derived() { System.out.println(“derived constructor"); System.out.println("n =" + n); System.out.println("npri =" + npri); System.out.println("npro =" + npro); System.out.println("npub =" + npub); } public void g() { f1(); f2(); f3(); f4(); }

  25. Example(4) public static void main(String args[]) { Protection pp = new Protection(); System.out.println("pp"); pp.f1(); pp.f2(); pp.f3(); pp.f4(); Derived dd = new Derived(); System.out.println("dd"); dd.f1(); dd.f2(); dd.f3(); dd.f4(); } } base constructor、n=1 npri=2、npro=3 、 npub=4、 pp f2-3、 f3-4、 f4-1 base constructor、n=1 npri=2、npro=3 、 npub=4、 derived constructor、 n=1、npro=3 、 npub=4、dd f2-3、 f3-4、 f4-1

  26. Example(5) package p1; Public class Nderived { public Nderived() { System.out.println(“nderived constructor”); System.out.println(“n = ” + n); System.out.println(“npri =” + npri); System.out.println(“npro =” + npro); System.out.println(“npub =” + npub); } private void ng() { f1(); f2(); f3(); f4(); System.out.println(“n = ” + n); System.out.println(“npri =” + npri); System.out.println(“npro =” + npro); System.out.println(“npub =” + npub); }

  27. Example(6) public static void main(String args[]) { Protection pp = new Protection(); System.out.println("pp"); pp.f1(); pp.f2(); pp.f3(); pp.f4(); Derived dd = new Derived(); System.out.println("dd"); dd.f1(); dd.f2(); dd.f3(); dd.f4(); } } base constructor、n=1 npri=2、npro=3 、 npub=4、 pp f2-3、 f3-4、 f4-1 base constructor、n=1 npri=2、npro=3 、 npub=4、 derived constructor、 n=1、npro=3 、 npub=4、dd f2-3、 f3-4、 f4-1

  28. Example(7) package p2; public class Derived2 extends p1.Protection{ public Derived2() { System.out.println(“derived other package constructor"); System.out.println("n =" + n); System.out.println("npri =" + npri); System.out.println("npro =" + npro); System.out.println("npub =" + npub); } public void g2() { f1(); f2(); f3(); f4(); System.out.println(“n = ” + n); System.out.println(“npri =” + npri); System.out.println(“npro =” + npro); System.out.println(“npub =” + npub); } System.out.println("npro =" + npro); f2();

  29. Example(8) public static void main(String args[]) { p1.Protection pp = new p1.Protection(); System.out.println("pp"); pp.f1(); pp.f2(); pp.f3(); pp.f4(); Derived2 ff = new Derived2(); System.out.println(“ff"); ff.f1(); ff.f2(); ff.f3(); ff.f4(); } } base constructor、n=1 npri=2、npro=3 、 npub=4、 pp、 f3-4 base constructor、n=1 npri=2、npro=3 、 npub=4、 derived other package constructor 、 npro=3 、npub=4、 ff 、 f2-3、f3-4 ff.f2();

  30. Example(9) package p2; public class Nderived2 { public Nderived2() { System.out.println(“derived other package constructor"); System.out.println("n =" + n); System.out.println("npri =" + npri); System.out.println("npro =" + npro); System.out.println("npub =" + npub); } public void ng2() { f1(); f2(); f3(); f4(); System.out.println(“n = ” + n); System.out.println(“npri =” + npri); System.out.println(“npro =” + npro); System.out.println(“npub =” + npub); }

  31. Example(10) public static void main(String args[]) { p1.Protection pp = new p1.Protection(); System.out.println("pp"); pp.f1(); pp.f2(); pp.f3(); pp.f4(); p1.Derived dd = new p1.Derived(); System.out.println("dd"); dd.f1(); dd.f2(); dd.f3(); dd.f4(); } } base constructor、n=1 npri=2、npro=3 、 npub=4、 pp、 f3-4 base constructor、n=1 npri=2、npro=3 、 npub=4、 derived constructor、 n=1、npro=3 、 npub=4、dd 、 f3-4

  32. Access Specifiers A access A’s public protected package Private import pkg1.*; Client D Client B import pkg1.*; Subclass E Subclass C Package pkg1; Package pkg2; B access A’s public protected* package D access A’s public Public ClassA Public void f1() Protected void f2() Void f3() Private void f4() E access A’s public protected C access A’s public protected package

  33. Example Class B { B() { }; public/protected/private/frendly void f() { } } Class D extends B { D(){}; void g() { f(); }; public static void main(String args[]) { B b = new B(); b.f(); } }

  34. Whether o.k. or error when compiling g()

  35. Whether o.k. or error when compiling main(String args[])

  36. Inner Classes(1) • An inner class is class defined within another class. • An inner class is an artifice of the compiler: • they are compiled into separate class files with names of the form: outerclass$innerclass.class so that the interpreter is unaware of them

  37. Inner Classes(2) • Why would you want to use inner classes? 1. Inner classes can access the implementation of the object that created it - including private data.2. Inner classes can be hidden from other classes in the same package.3. Anonymous inner classes are handy when you want to define callbacks on the fly.4. Inner classes are very convenient when you are writing event-driven programs.

  38. Inner Classes Example • class Outer { int n; class Inner { int ten = 10; void setNToTen ( ) { n = 10; } } void setN ( ) { new Inner ( ).setNToTen ( ); }}

  39. Understanding of Inner Class class Enclosing{ private int a; private int b; private class Inner{ private int c; private int d; } } … Enclosing T1 = new Enclosing(); Inner T2 = new Inner(); class Supperclass{ private int a; private int b; } class Subclass extends Supperclass { private int c; private int d; } … Supperclass S1 = new Supperclass(); Subclass S2 = new Subclass(); T1.a T1.b S1.a S1.b T1.a T1.b T2.c T2.d S2.a S2.b S2.c S2.d

  40. Types of Inner classes • Instance inner classes(Member classes) • classes which are non-static members of an enclosing class • Local inner classes (not too useful) • classes which are local to a method within an enclosing class • Anonymous inner classes • local inner classes without a name • Static inner classes (NestedClass , not too useful) • classes which are static members of an enclosing class

  41. Instance Inner Classes (1) • Non-static • An instance inner class can only be referenced via an object of the enclosing class • An instance inner class can reference instance members of the enclosing class, including private members • Example1 • We can create an Inner class object by three ways: • create directly in methods of the Outer class • create in static methods of the Outer class • create in methods of the other class

  42. this Revisited • To support instance classes several extra expressions are provided • x = this.dataMember is valid only • • if dataMember is an instance variable declared by the instance inner class • • not if dataMember belongs to the enclosing class • x = EnclosingClass.this.dataMember allows access to a dataMember that belongs to the enclosing class • Inner classes can be nested to any depth and the this mechanism can be used with nesting

  43. Instance Inner Classes(2) • Instance inner classes are useful for handling events • Button b = new Button (“Click Me”);b.addActionListener (new Clicker ( ));…class Clicker implements ActionListener { … } • Can access the variables of the outer class

  44. Local Inner Classes • are defined within a method (or other block), like a local variable • can only be referenced within that block • can reference local variables of the class • can reference instance variables of the enclosing class • can reference final local variables of the enclosing block • Example

  45. Anonymous Inner Classes(1) • An anonymous class: – is a local class that does not have a name. – allows an object to be created using an expression that combines object creation with the declaration of the class • Declaring an anonymous class avoids naming the class – Can only ever create one instance of the anonymous class. • This is handy in the AWT

  46. Anonymous Inner Classes(2) • An anonymous class is defined as part of a new expression and must be a subclass or implement an interface. • new className( argumentList ) { classBody } • new interfaceName() { classBody } • The class body can define methods but cannot define any constructors. • The restrictions imposed on local classes also apply.

  47. Example of Anonymous Inner Class b.addActionListener (new ActionListener ( ) { public void actionPerformed (ActionEvent e) { System.out.println (“Ouch!”); } } );

  48. Static Inner Classes(1) [public] [modifier] class enclosing_name { [access_specifier] [modifier] static class enclosed_name{…}… } • The syntax of the enclosing class or interface definition is like any class or interface definition • You can declare nested classes to be public、protected 、package or private • Classes nested within interfaces are implicitly static, like fields defined in interfaces • The qualifiers abstract and final have their usual meaning when applied to nested classes

  49. Static Inner Classes(2) • A static inner class must be a top-level class, because a static inner class has not a reference to it’s outside class • A static inner class can access only static variables of the enclosing class • If you do not want to use a inner class reference the object of it’s outside class , and only want to hide a class inside another class,you may use a static inner class • Example

  50. Example of Static Inner Classes Class Outer { public static class Inner{ int m1; int m2; } public static Inner method() { Inner i = new Inner(); i.m1++; i.m2--; return i; } } public class StaticInnerClassTest { public static void main(String[] args) { Outer.Inner i = Outer.method(); Sysytem.out.println(“m1=“ + i.m1); Sysytem.out.println(“m2=“ + i.m2); } }

More Related