gpt4 book ai didi

Java:与接口(interface)、抽象类或内部类的可重用封装?

转载 作者:行者123 更新时间:2023-11-29 08:18:08 25 4
gpt4 key购买 nike

我尝试封装。接口(interface)异常,静态内部类工作,非静态内部类不工作,无法理解术语:嵌套类,内部类,嵌套接口(interface),接口(interface)抽象类——听起来太重复了!

糟糕! --- 接口(interface)中的异常“非法类型”显然是因为值是常量(?!)

    static interface userInfo
{
File startingFile=new File(".");
String startingPath="dummy";
try{
startingPath=startingFile.getCanonicalPath();
}catch(Exception e){e.printStackTrace();}
}

多种方式:接口(interface)、静态内部类图像 VS 非静态内部类图像

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!

相关

最佳答案

问题是您在方法之外编写代码。你确实需要一个类,你必须把你的代码放在一个方法中。例如:

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 约定,类和接口(interface)以大写字母开头。

编辑:描述您最近对问题的评论:

当你想强制类似的类(想想不同类型的 DVD 播放器)具有相同的基本功能(播放 DVD、停止、暂停)时使用接口(interface)。你类似地使用抽象类,但是当所有的类都将实现一些相同的事情以相同的方式进行。

关于Java:与接口(interface)、抽象类或内部类的可重用封装?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2734903/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com