我试着封装。从接口出发,静态内部类工作,非静态内部类不工作,无法理解术语:嵌套类,内部类,嵌套接口,接口抽象类--听起来太重复了!
坏!-显然是因为值是常量(?!)而导致接口中的“非法类型”例外。
static interface userInfo
{
File startingFile=new File(".");
String startingPath="dummy";
try{
startingPath=startingFile.getCanonicalPath();
}catch(Exception e){e.printStackTrace();}
}实现IT的多种方法:接口、静态内部类映像和非静态内部类映像。
import java.io.*;
import java.util.*;
public class listTest{
public interface hello{String word="hello word from Interface!";}
public static class staticTest{
staticTest(){}
private String hejo="hello hallo from Static class with image";
public void printHallooo(){System.out.println(hejo);}
}
public class nonStatic{
nonStatic(){}
public void printNonStatic(){System.out.println("Inside non-static class with an image!");}
}
public static class staticMethodtest{
private static String test="if you see mee, you printed static-class-static-field!";
}
public static void main(String[] args){
//INTERFACE TEST
System.out.println(hello.word);
//INNNER CLASS STATIC TEST
staticTest h=new staticTest();
h.printHallooo();
//INNER CLASS NON-STATIC TEST
nonStatic ns=(new listTest()).new nonStatic();
ns.printNonStatic();
//INNER CLASS STATIC-CLASS STATIC FIELD TEST
System.out.println(staticMethodtest.test);
}
}输出
hello word from Interface!
hello hallo from Static class with image
Inside non-static class with an image!
if you see mee, you printed static-class-static-field!相关
发布于 2010-04-29 06:28:57
问题是,您正在编写方法之外的代码。为此您确实需要一个类,并且必须将代码放入一个方法中。例如:
static class UserInfo
{
public static void myMethod()
{
File startingFile = new File(".");
String startingPath = "dummy";
try
{
startingPath = startingFile.getCanonicalPath();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}这确实假定java.io.File是导入的。
然后可以调用UserInfo.myMethod();
您还可能希望导入java.util.IOException并捕获一个IOException,而不是一般的异常。
此外,类和接口以Java约定的大写字母开头。
编辑:描述你最近对你的问题的评论:
当您想要强制类似的类(考虑不同类型的DVD播放机)具有相同的基本功能(播放DVD、停止、暂停)时,请使用接口。您使用抽象类的方式类似,但是当所有类都以相同的方式实现一些相同的东西时。
发布于 2010-04-29 05:24:17
我觉得你想这么做
static class userInfo
{
public static void something() {
File startingFile=new File(".");
String startingPath="dummy";
try{
startingPath=startingFile.getCanonicalPath();
}catch(Exception e){e.printStackTrace();}
}
}发布于 2010-04-29 05:13:21
不能将代码放在接口中,接口只描述对象的行为。即使在使用类时,也应该将此类代码放在方法中,而不是直接放在类主体中。
https://stackoverflow.com/questions/2734903
复制相似问题