Java:为什么声明在界面上不够用?

hhh*_*hhh 1 java initialization interface declaration

大类包含Format-interfcase和Format-class.Format-class包含方法,接口具有字段的值.我可以在类Format中使用字段,但目标是使用Interface.那么我只是创建虚拟变量以消除错误,设计问题或ELSE?

KEY:声明VS初始化

  1. 通过术语解释,为什么你必须在接口中初始化.
  2. 它背后的逻辑是什么?
  3. 它引导界面使用哪种问题?

示例代码具有init-interface-problem

import java.util.*;
import java.io.*;

public class FormatBig
{

        private static class Format implements Format
        {
                private static long getSize(File f){return f.length();}
                private static long getTime(File f){return f.lastModified();}
                private static boolean isFile(File f){if(f.isFile()){return true;}}
                private static boolean isBinary(File f){return Match.isBinary(f);}
                private static char getType(File f){return Match.getTypes(f);}
                private static String getPath(File f){return getNoErrPath(f);}
                //Java API: isHidden, --- SYSTEM DEPENDED: toURI, toURL


                Format(File f)
                {
                  // PUZZLE 0: would Stack<Object> be easier?
                        size=getSize(f);
                        time=getTime(f);
                        isfile=isFile(f);
                        isBinary=isBinary(f);
                        type=getType(f);
                        path=getPath(f);

                    //PUZZLE 1: how can simplify the assignment?
                        values.push(size);
                        values.push(time);
                        values.push(isfile);
                        values.push(isBinary);
                        values.push(type);
                        values.push(path);
                }
        }

        public static String getNoErrPath(File f)
        {
                try{return f.getCanonicalPath();
                }catch(Exception e){e.printStackTrace();}
        }

        public static final interface Format
        {
                //ERR: IT REQUIRES "="
                public long size;
                public long time;
                public boolean isFile=true;   //ERROR goes away if I initialise wit DUMMY
                public boolean isBinary;
                public char type;
                public String path;
                Stack<Object> values=new Stack<Object>();
        }

        public static void main(String[] args)
        {
                Format fm=new Format(new File("."));
                for(Object o:values){System.out.println(o);}
        }
}
Run Code Online (Sandbox Code Playgroud)

Tom*_*ine 6

接口中的字段是隐式的public final static.

static意味着他们独立于实例.这可能不是你想要的.

final意味着它们需要在课程初始化期间分配一次,因为字段也是如此static.这通常意味着在声明中进行分配,但可以使用静态初始化器.如果它们是实例字段(非static),则需要在声明,构造函数(隐式或显式调用super而不是" this"构造函数)或实例初始化器中分配它们.

您应该将实例字段移动到实现类中,并标记它们final.