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 - PowerPoint PPT Presentation
Citation preview
Ch1 Introduction Lecture6
What are Interfaces
An interface is a type, which is only made up of abstract methods
and constants
Interfaces
Declaration
[<type> <final-var> = <value>; ]*} // []* -- 0 or
many times
Methods: abstract, public, native
There are no constructors in interfaces
Interface types may be used to declare variables
Programming in Java
Attr remove(String
java.util.Enumeration attrs();
interface Verbose {
Specify the methods need to be implemented by many classes
Understand the interactive interfaces of objects, instead of the
classes of objects
Function
[6-*]
An interface is actually meaningful only when it has been
implemented by a class
class <classname> [extends <superclass>]
interface Callback {
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 may implement several 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
Notes
else if (prob<70) return YES;
else return NEVER;}
public void add(Attr newAttr) {
Conflict: X(m),Y(m)—Z(m?)
Interface and Specification
[6-*]
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; // … }
Interface Inheritance(2)
[6-*]
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
Conflict Resolution(1)
} // 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
Conflict Resolution(2)
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)
Interfaces and Classes
Programming in Java
public abstract String getName(); }
protected double x,y //coordinates of the circle
public Point(douleb a, double b) {setPoint(a,b);}
public void setPoint (douleb a, double b) {
x = a; y = b; }
Programming in Java
protected double radius;
{super(a,b); setRadius(r) ; }
public double area() {return 3.14159*radius*radius;}
public String getName {return “Circle”;} }
public class Cylinder extends Circle{
protected double height; //height ofCylinder
……
CanFight, CanSwim, CanFly {
public void swim() { }
public void fly() { } }
public class Adventure {
Hero i = new Hero();
t(i) ; u(i) ; v(i) ; w(i) ;} }
[6-*]
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)
Interfaces, Classes and Types
[6-*]
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)
Packages
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>”)
The Package Statement
Programming in Java
E:\javafile>md p1
E:\javafile>md p2
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
Example(1)
While compiling PackageTest.java, Compiler will search in these
ways
test\ASC.class inside c:\jdk\lib\classes.zip
c:\class\test\ABC.class
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
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
Syntax import pkg1[.pkg2].(<classname>|*);
Example
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
Access Protection
Protection pp = new Protection();
public Derived() {
Protection pp = new Protection();
Protection pp = new Protection();
public Derived2() {
System.out.println("n =" + n);
System.out.println("npri =" + npri);
System.out.println("npro =" + npro);
System.out.println("npub =" + npub); }
p1.Protection pp = new p1.Protection();
System.out.println("n =" + n);
System.out.println("npri =" + npri);
System.out.println("npro =" + npro);
System.out.println("npub =" + npub); }
p1.Protection pp = new p1.Protection();
Public ClassA
Package pkg2;
E access A’s public protected
Client B
Subclass C
import pkg1.*;
Client D
import pkg1.*;
Subclass E
B b = new B();
Modifier Relation of B&D
No Modifier
Modifier Relation of B&D
No Modifier
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
Programming in Java
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.
Programming in Java
Local inner classes (not too useful)
classes which are local to a method within an enclosing class
Anonymous inner classes
Static inner classes (NestedClass , not too useful)
classes which are static members of an enclosing class
Programming in Java
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
Programming in Java
Outer o = new Outer();
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
Programming in Java
Button b = new Button (“Click Me”);
b.addActionListener (new Clicker ( ));
Programming in Java
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
class Outer {
int LocalVar = 6;
LocalVar + */ “finalLocalVar =” + finalLocalVar+ “>”);} }
return new Inner();}}
public class OuterTest {
Outer outer = new Outer();
– 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
Programming in Java
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.
Programming in Java
b.addActionListener (new ActionListener ( ) {
{
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 publicprotected 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
Programming in Java
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
Class Outer {
Outer.Inner i = Outer.method();
Sysytem.out.println(“m1=“ + i.m1);
Sysytem.out.println(“m2=“ + i.m2);