这个问题不是接口的问题而是关于静态声明static的概念。 1、java里所有static声明会在程序运行前被分配好。因此在main函数真正执行前,程序里已经有main函数和p存在了。 2、对于static test p,因为test是个对象,所以这句话并不能生成一个test的实例。但却生成了静态变量p(注意是变量p,而不是对象,只是个test对象的引用)。 3、对于类来说,其类变量(如程序里的i)会在调用类构造函数前被定义。但类的方法却不会在此时被定义。所以当声明static test p时候test的i已经存在,而fun却没有。 4、接口和类在处理这个问题上是一样的。 望各位高手指导。
不是吧,接口用来这样实现,有没有搞错!!!! 我是这么写的,,, interface test { void fun(); } public class Aaa { public void display(test t) { t.fun(); } } public class Bbb implements test { public void fun() { System.out.println("hello world"); } } public class ccc { public static void main(String args[]) { Aaa a=new Aaa(); a.display(new Bbb()); } }
interface tes { void fun(); } public class test { public static void main(String args[]) { test a=new test(); a.display(new tes(){ public void fun() { System.out.println("hello world"); } }); }
class test { static int i = 100; static void fun() { System.out.println("heihei"); } } public class tes { static test p; public static void main(String []args) { System.out.println(p.i); test.fun(); } }在java里面象这样定义static test p;是不是就象在C++里面 test p;一样啊,p 就是对象本身
p.fun();//--------------------------------- 3
2没错啊,输出p.i i是接口的field,其实就是输出静态接口的属性;test是个静态接口,不能直接调用接口的方法fun(),所以3会出错;static 不能在方法内部进行定义。
1、java里所有static声明会在程序运行前被分配好。因此在main函数真正执行前,程序里已经有main函数和p存在了。
2、对于static test p,因为test是个对象,所以这句话并不能生成一个test的实例。但却生成了静态变量p(注意是变量p,而不是对象,只是个test对象的引用)。
3、对于类来说,其类变量(如程序里的i)会在调用类构造函数前被定义。但类的方法却不会在此时被定义。所以当声明static test p时候test的i已经存在,而fun却没有。
4、接口和类在处理这个问题上是一样的。
望各位高手指导。
我是这么写的,,,
interface test
{
void fun();
}
public class Aaa
{ public void display(test t)
{
t.fun();
}
}
public class Bbb implements test
{
public void fun()
{
System.out.println("hello world");
}
}
public class ccc
{
public static void main(String args[])
{
Aaa a=new Aaa();
a.display(new Bbb());
}
}
{
void fun();
}
public class test
{
public static void main(String args[])
{
test a=new test();
a.display(new tes(){
public void fun()
{
System.out.println("hello world");
}
});
}
void display(tes t)
{
t.fun();
}
}如果要是思想的话,我觉得我会这样写,我想知道的是qqbz(qqbz)说的。
抽象类是不可以被实例化的
而你用static就使编译器以为你定义的是一个test类型的变量p,而不是对象
{
static int i = 100;
static void fun()
{
System.out.println("heihei");
}
}
public class tes
{
static test p;
public static void main(String []args)
{
System.out.println(p.i);
test.fun();
}
}在java里面象这样定义static test p;是不是就象在C++里面 test p;一样啊,p 就是对象本身