1Java 的多重继承与内部类

<!-- @page { margin: 2cm } P { margin-bottom: 0.21cm } -->

  1. Java 的多重继承

    1. Interface 不与任何存储空间有关联,可以合并多个 interface

组合多个接口和一个具体类

/: c08:Adventure.java

// Multiple interfaces.

import java.util.*;

 

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() {} // 继承来自 CanFight 因为接口继承过来的一定还是接口

}

 

public class Adventure {

static void t(CanFight x) { x.fight(); }

static void u(CanSwim x) { x.swim(); }

static void v(CanFly x) { x.fly(); }

static void w(ActionCharacter x) { x.fight(); } // ActionCharacter 是个实体类

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

}

} ///:~

 

In class Adventure , you can see that there are four methods that take as arguments the various interfaces and the concrete class. When a Hero object is created, it can be passed to any of these methods, which means it is being upcast to each interface in turn

 

  1. 合并接口名称冲突问题

//: c08:InterfaceCollision.java

 

interface I1 { void f(); }

interface I2 { int f(int i); }

interface I3 { int f(); }

class C { public int f() { return 1; } }

 

class C2 implements I1, I2 {

public void f() {}

public int f(int i) { return 1; } // overloaded

}

// I2 方法, int f(int i) C 中方法 int f()

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; }

}

 

重载函数,无法仅仅靠返回型别来区分作为区分

C 中方法为 int f(), i1 方法是 void f()

// Methods differ only by return type:

//! class C5 extends C implements I1 {}

//! interface I4 extends I1, I3 {} ///:~

 

错误如下:

InterfaceCollision.java:23: f() in C cannot

implement f() in I1; attempting to use

incompatible return type

found : int

required: void

InterfaceCollision.java:24: interfaces I3 and I1 are incompatible; both define f

(), but with different return type

 

  1. 通过继承来扩充接口

//: c08:HorrorShow.java

// Extending an interface with inheritance.

 

interface Monster {

void menace();

}

// 扩充 Monster 得到一个新的 interface

interface DangerousMonster extends Monster {

void destroy();

}

 

interface Lethal {

void kill();

}

// 实现

class DragonZilla implements DangerousMonster {

public void menace() {}

public void destroy() {}

}

//extends 只能用于单一类,但是可以用来制作新的 interface

interface Vampire

extends DangerousMonster, Lethal {

void drinkBlood();

}

 

class HorrorShow {

static void u(Monster b) { b.menace(); }

static void v(DangerousMonster d) {

d.menace();

d.destroy();

}

public static void main(String[] args) {

DragonZilla if2 = new DragonZilla();

u(if2); // 向上转型 Monster

v(if2); // 向上转型 DangerousMonster

}

} ///:~

  1. 接口 interfaces 内数据成员初始化

定义于接口中的数据成员会自动成为 static final ,并且自动成为 public

//: c08:RandVals.java

// Initializing interface fields with

// non-constant initializers.

import java.util.*;

 

public interface RandVals {

int rint = (int )(Math.random() * 10);

long rlong = (long )(Math.random() * 10);

float rfloat = (float )(Math.random() * 10);

double rdouble = Math.random() * 10;

} ///:~

 

Since the fields are static , they are initialized when the class is first loaded, which happens when any of the fields are accessed for the first time. Here’s a simple test:

//: c08:TestRandVals.java

 

public class TestRandVals {

public static void main(String[] args) {

System.out.println(RandVals.rint);

System.out.println(RandVals.rlong);

System.out.println(RandVals.rfloat);

System.out.println(RandVals.rdouble);

}

} ///:~

The fields, of course, are not part of the interface but instead are stored in the static storage area for that interface.

  1. 嵌套 Interfaces

接口 可位于某个class 或者 其他接口内部

 

//: c08:NestingInterfaces.java

 

class A {

interface B {

void f();

}

public class BImp implements B {

public void f() {}

}

private class BImp2 implements B {

public void f() {}

}

public interface C {

void f();

}

class CImp implements C {

public void f() {}

}

private class CImp2 implements C {

public void f() {}

}

private interface D {

void f();

}

private class DImp implements D {

public void f() {}

}

public class DImp2 implements D {

public void f() {}

}

public D getD() { return new DImp2(); }

private D dRef;

public void receiveD(D d) {

dRef = d;

dRef.f();

}

}

 

interface E {

interface G {

void f();

}

// Redundant "public":

public interface H {

void f();

}

void g();

// Cannot be private within an interface:

//! private interface I {}

}

 

public class NestingInterfaces {

public class BImp implements A.B {

public void f() {}

}

class CImp implements A.C {

public void f() {}

}

// Cannot implement a private interface except

// within that interface's defining class:

//! class DImp implements A.D {

//! public void f() {}

//! }

class EImp implements E {

public void g() { }

}

class EGImp implements E.G {

public void f() { }

}

class EImp2 implements E {

public void g() {}

class EG implements E.G {

public void f() {}

}

}

public static void main(String[] args) {

A a = new A();

// Can't access A.D:

//! A.D ad = a.getD();

// Doesn't return anything but A.D:

//! A.DImp2 di2 = a.getD();

// Cannot access a member of the interface:

//! a.getD().f();

// Only another A can do anything with getD():

A a2 = new A();

a2.receiveD(a.getD());

}

} ///:~

 

 

 

  1. inner class 理解

 

一、什么是嵌套类及内部类?
    
可以在一个类的内部定义另一个类,这种类称为嵌套类(nested classes, 它有两种类型:
静态嵌套类和非静态嵌套类。静态嵌套类使用很少,最重要的是非静态嵌套类,也即是被称作为
内部类(inner) 。嵌套类从JDK1.1 开始引入。其中inner 类又可分为三种:
    
其一、在一个类(外部类)中直接定义的内部类;
    
其二、在一个方法(外部类的方法)中定义的内部类;
    
其三、匿名内部类。
下面,我将说明这几种嵌套类的使用及注意事项。
二、静态嵌套类
    
如下所示代码为定义一个静态嵌套类,

public class StaticTest {


private static String name = "java ";
private String id = "001";

static class Person{
private String address = "usa ,english,china";
public String mail = "yaya @yahoo.com";//
内部类公有成员
public void display(){
//System.out.println(id);//
不能直接访问外部类的非静态成员
System.out.println(name);//
只能直接访问外部类的静态成员
System.out.println("Inner "+address);//
访问本内部类成员。
}
}

public void printInfo(){
Person person = new Person();
person.display();

// 外部类访问内部类的的成员有些特别,不能直接访问,但可以通过内部类来访问
//System.out.println(mail);//
不可访问
//System.out.println(address);//
不可访问

System.out.println(person.address);//
可以访问内部类的私有成员
System.out.println(person.mail);//
可以访问内部类的公有成员

}
public static void main(String[] args) {
StaticTest staticTest = new StaticTest();
staticTest.printInfo();
}
}
总结:在静态嵌套类内部,不能访问外部类的非静态成员,这是由Java 语法中" 静态方法不能直接访问非静态成员" 所限定。
若想访问外部类的变量,必须通过其它方法解决,由于这个原因,静态嵌套类使用很少。注意,外部类访问内部类的的成员有些特别,不能直接访问,但可以通过内部类来访问,这是因为静态嵌套内的所有成员和方法默认为
静态的了。同时注意,内部静态类Person 只在类StaticTest  范围内可见,若在其它类中引用或初始化,均是错误的。


三、在外部类中定义内部类
    
如下所示代码为在外部类中定义两个内部类及它们的调用关系:
public class Outer{
int outer_x = 100;
class Inner{
public int y = 10;
private int z = 9;
int m = 5;
public void display(){
System.out.println("display outer_x:"+ outer_x);
}
private void display2(){
System.out.println("display outer_x:"+ outer_x);
}
}
void test(){
Inner inner = new Inner();
inner.display();
inner.display2();
//System.out.println("Inner y:" + y);//
不能访问内部内变量
System.out.println("Inner y:" + inner.y);//
可以访问
System.out.println("Inner z:" + inner.z);//
可以访问
System.out.println("Inner m:" + inner.m);//
可以访问
InnerTwo innerTwo = new InnerTwo();
innerTwo.show();
}
class InnerTwo{
Inner innerx = new Inner();
public void show(){
//System.out.println(y);//
不可访问Innter y 成员
//System.out.println(Inner.y);//
不可直接访问Inner 的任何成员和方法

 

// Inner 内部类的变量成员只在内部内内部可见, 若外部类或同层次的内部类 InnerTwo 需要访问,需采用示例程序中的方法,不可直接访问内部类的变量。
innerx.display();//
可以访问
innerx.display2();//
可以访问
System.out.println(innerx.y);//
可以访问
System.out.println(innerx.z);//
可以访问
System.out.println(innerx.m);//
可以访问
}
}


public static void main(String args[]){
Outer outer = new Outer();
outer.test();
}
}

 

总结:对于内部类,通常在定义类的class 关键字前不加public  或 private 等限制符,若加了
没有任何影响,同时好像这些限定符对内部类的变量和方法也没有影响(?) 。另外,就是要注意,内部类InnerInnterTwo 只在类Outer 的作用域内是可知的,如果类Outer 外的任何代码尝试初始化类Inner 或使用它,编译就不会通过。同时,内部类的变量成员只在内部内内部可见,若外部类或同层次的内部类需要访问,需采用示例程序中的方法,不可直接访问内部类的变量。

四、在方法中定义内部类
    
如下所示代码为在方法内部定义一个内部类:

public class FunOuter {
int out_x = 100;
public void test(){
class Inner{
String x = "x";
void display(){
System.out.println(out_x);
}
}
Inner inner = new Inner();
inner.display();
}

public void showStr(String str){
//public String str1 = "test Inner";//
不可定义,只允许final 修饰
//static String str4 = "static Str";//
不可定义,只允许final 修饰
String str2 = "test Inner";
final String str3 = "final Str";
class InnerTwo{
public void testPrint(){
System.out.println(out_x);//
可直接访问外部类的变量
//System.out.println(str2);//
不可访问本方法内部的非final 变量
System.out.println(str3);//
只可访问本方法的final 型变量成员
}
}
InnerTwo innerTwo = new InnerTwo();
innerTwo.testPrint();
}

public void use(){
//Inner innerObj = new Inner();//
此时Inner 己不可见了。
//System.out.println(Inner.x);//
此时Inner 己不可见了。
}


public static void main(String[] args) {
FunOuter outer = new FunOuter();
outer.test();
}
}

从上面的例程我们可以看出定义在方法内部的内部类的可见性更小,它只在方法内部
可见,在外部类( 及外部类的其它方法中) 中都不可见了。同时,它有一个特点,就是方法
内的内部类连本方法的成员变量都不可访问,它只能访问本方法的final 型成员。 同时另一个需引起注意的是方法内部定义成员,只允许final 修饰或不加修饰符,其它像static 等均不可用。


五、匿名内部类
    
如下所示代码为定义一个匿名内部类: 匿名内部类通常用在Java 的事件处理上
import java.applet.*;
import java.awt.event.*;

    public class AnonymousInnerClassDemo extends Applet{
    public void init(){
        addMouseListener(new MouseAdapter(){
            public void mousePressed(MouseEvent me){
             showStatus("Mouse Pressed!");
        }
        }
)
    }
    public void showStatus(String str){
        System.out.println(str);
    }
    }

在上面的例子中,方法addMouseListener 接受一个对象型的参数表达式,于是,在参数里,我们定义了一个匿名内部类, 这个类是一个MouseAdapter 类型的类 ,同时在这个类中定义了一个继承的方法mousePressed ,整个类做为一个参数。这个类没有名称,但是当执行这个表达式时它被自动实例化。同时因为,这个匿名内部类是定义在AnonymousInnerClassDemo  类内部的,所以它可以访问它的方法showStatus 。这同前面的内部类是一致的。


六、内部类使用的其它的问题
通过以上,我们可以清楚地看出内部类的一些使用方法,同时,在许多时候,内部类是在如Java 的事件处理、或做为值对象来使用的。同时,我们需注意最后一个问题,那就是,内部类同其它类一样被定义,同样它也可以继承外部其它包的类和实现外部其它地方的接口。同样它也可以继承同一层次的其它的内部类 , 甚至可以继承外部类本身。下面我们给出最后一个例子做为结束:
public class  Layer {
//Layer
类的成员变量
private String testStr = "testStr";

//Person
类,基类 ---------------------------------------------------
class  Person{
String name;
Email email;
public void setName(String nameStr){
this.name = nameStr;
}
public String getName(){
return this.name;
}
public void setEmail(Email emailO

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值