java之接口实例化

1 接口无法进行实例化。不过接口可以通过匿名接口来操作。直接实现一个接口。但是是匿名的
如:public interface Test1Interface {
public int aa=1;
public void run();
}




public class Test1 {


private Test1Interface test1Interface=null;


public Test1() {
super();
// TODO Auto-generated constructor stub
}


public Test1(Test1Interface test1Interface) {
super();
this.test1Interface = test1Interface;
}

public void start(){
if(this.test1Interface!=null){
this.test1Interface.run();
}

}
}


//测试  接口匿名类 直接实现一个接口。但是是匿名的
Test1 test1=new Test1(new Test1Interface(){//匿名的实现接口


public void run() {
// TODO Auto-generated method stub
System.out.println("11111");
}

});
test1.start();


2 接口的属性默认都是public、static、final类型的。
如:/**
* 接口变量 
* 只能是public(公共的,private的类型,只能在接口中使用,但是接口都是方法申明而没有方法体) 
* static类型的(是因为只能通过接口类名类使用。而无法接口自身实例化来调用),
* final类型的(不能被修改)
* 故只能是public、static、final类型的
*/


public interface Test1Interface {
public int aa=1;
public void run();
}


3 接口无法实例化。不过实现接口的子类可以通过创建对象赋值给接口。
如:public interface Commond {



public void process();
}


public class RegisterImpl implements Commond{


public void process() {
// TODO Auto-generated method stub
System.out.println("注册。。。。");
}


}


//实现接口的类通过创建对象赋值给接口
Commond commond=new RegisterImpl();
commond.process();


4 接口对象实例化后(通过实现接口的类创造对象赋值给接口)。如果想要赋值给实现接口的子类。需要通过强制转换。
如:Commond commond=new RegisterImpl();
commond.process();

RegisterImpl registerImpl=(RegisterImpl)commond;
registerImpl.process();




5 通过子类的类名的全路径。可以得到class、继而得到类对象。然后调用接口方法。类名-》class->Object类对象
如:String className="test.sample2.impl.RegisterImpl";
Class class_=(Class) Class.forName(className);
Commond commond_=class_.newInstance();//通过newInstance()得到对象。
commond_.process();


6 接口也可以作为参数进行传递来使用。
如:public interface ICommond {


public void sendCommond();
}


public class CommondImpl implements ICommond{


public void sendCommond() {
// TODO Auto-generated method stub
System.out.println("发送命令....");
}


}




public class TestCommond {


private ICommond commond=null;

public TestCommond() {
super();
// TODO Auto-generated constructor stub
}


public TestCommond(ICommond commond) {
super();
this.commond = commond;
}

public void sendCommond(){
if(this.commond!=null){
this.commond.sendCommond();
}
}



}


//首先是将实现接口的子类创造对象赋值给接口。然后将该接口作为参数传递。最后调用方法,该方法中调用该接口的方法
ICommond commond=new CommondImpl();
TestCommond test=new TestCommond(commond);
test.sendCommond();




综上所述:接口的功能:
1 匿名类
2 成员变量:public static final  简称:psf
3 接口的实例化(实现接口的子类创造对象赋值给接口)
4 接口的赋值(由接口赋值给实现接口的子类。通过强制转换)
5 通过实现接口的子类的全路径来得到class。然后得到接口对象。最后调用接口方法。
6 把接口当做参数传递并最后调用方法。

你可能感兴趣的:(java之接口实例化)