Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/366.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何正确编写extends功能而不是import语句?_Java - Fatal编程技术网

Java 如何正确编写extends功能而不是import语句?

Java 如何正确编写extends功能而不是import语句?,java,Java,我使用的不是import语句,而是java.util.Scanner类的extends属性。下面的代码片段出现错误。如何更正它 class test extends java.util.Scanner { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the value from keyboard:")

我使用的不是import语句,而是java.util.Scanner类的extends属性。下面的代码片段出现错误。如何更正它

 class test extends java.util.Scanner {
    public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the value from keyboard:");
      int ans = sc.nextInt();
      System.out.println("The value entered through keyboard ::"+ans);
    }
 }

简短回答:您不能这样做,因为java.util.Scanner是最终版本,您无法扩展它

但是,您可以按如下方式使用封装,在同一个包中创建一个新类MyScanner:

import java.io.InputStream;
import java.util.Scanner;

public class MyScanner implements Iterator<String>, Closeable {

    private Scanner scanner;

    public MyScanner(InputStream in) {
        this.scanner = new Scanner(in);
    }

    //Override classes you need

}

请注意,这里的解决方案是在同一个包中声明两个类

您不能扩展
Scanner
类,因为它是最终类

即使有可能,扩展
Scanner
也不允许在引用不带包名的
Scanner
类时删除
import
语句

为给定代码扩展
扫描仪
是没有意义的。如果要避免使用
import
语句,请使用完整的类名:

class test
{
    public static void main(String[] args)
    {
        java.util.Scanner sc = new java.util.Scanner(System.in);
        System.out.println("Enter the value from keyboard:");
        int ans = sc.nextInt();
        System.out.println("The value entered through keyboard ::"+ans);
    }
}

Scanner
是一个
final
类,因此不能扩展

如果要在不明确导入扫描仪的情况下使用扫描仪,可以尝试以下操作:

class Test
{
    public static void main(String[] args)
    {
        java.util.Scanner sc = new java.util.Scanner(System.in); // Specify full class path over here
        System.out.println("Enter the value from keyboard:");
        int ans = sc.nextInt();
        System.out.println("The value entered through keyboard ::"+ans);
    }
}

请记住命名约定:类名应以大写字母开头。

这不是您处理问题的方式,即使如此,您仍然需要执行
import
我认为您正在寻找不,您不需要导入。您可以完全限定每个引用。但即便如此,扫描仪仍是最终的选择。您可以将其包装(见下文)并实现适当的接口,但不能在已经使用scanner的调用中用类替换scanner
class Test
{
    public static void main(String[] args)
    {
        java.util.Scanner sc = new java.util.Scanner(System.in); // Specify full class path over here
        System.out.println("Enter the value from keyboard:");
        int ans = sc.nextInt();
        System.out.println("The value entered through keyboard ::"+ans);
    }
}