没有修饰符的类默认不能访问声明为public的子类? Java

问题描述

我只是在Hackerrank上进行练习,因为我对Java还是很陌生(我只对C和C ++经验丰富,而Python / Matlab / C#最少)。基本上,我们只需要从头开始编写下面的“ Checker类”。但是,我注意到将public添加到Checker类时会导致运行时错误。有人知道为什么吗?我在网上找不到任何答案。

此外,是的,我知道访问修饰符对它们可以访问类的范围的限制,但是对于默认类如何无法访问公共类的方法,这对我来说没有任何意义。我假设这可能是我在实现一个导致问题的父类?这是我在Hackerrank上收到的RE消息:

Error: Main method not found in class Checker,please define the main method as:
   public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

如果有兴趣,请链接到练习题以供参考:https://www.hackerrank.com/challenges/java-comparator/problem

import java.util.*;

// Write your Checker class here
class Checker implements Comparator<Player>{  //If I add "public" in front I get RE
    @Override
    public int compare(Player A,Player B){
        if(A.score == B.score)
            return A.name.compareTo(B.name);
        else
            return B.score - A.score;
        // return A.compareTo(B);
    }
    
}

class Player{
    String name;
    int score;
    
    Player(String name,int score){
        this.name = name;
        this.score = score;
    }
}

class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();

        Player[] player = new Player[n];
        Checker checker = new Checker();
        
        for(int i = 0; i < n; i++){
            player[i] = new Player(scan.next(),scan.nextInt());
        }
        scan.close();

        Arrays.sort(player,checker);
        for(int i = 0; i < player.length; i++){
            System.out.printf("%s %s\n",player[i].name,player[i].score);
        }
    }
}

解决方法

有趣的问题,但我在整个职业生涯中从未使用过。

如果源文件中没有公共类,则main方法可以 放在任何类中,我们可以给源文件起任何名字。

来源:https://dzone.com/articles/why-single-java-source-file-can-not-have-more-than

由于@Andy Turner的话,我对其进行了进一步测试,实际上您可以在其他类(公共类除外)中使用main方法。这一切都取决于您如何称呼它:

package sample;

class Problem  {
    public static void main(String[] args) {
        System.out.println("main of Problem");
    }

}

public class Solution {
    public static void main(String[] args) {
        System.out.println("main of Solution");
    }
}

源文件名必须为Solution.java,因为这是公共类,但是您可以调用两个主要方法:

  > java sample.Solution  
  main of Solution
 
  > java sample.Problem
  main of Problem

从解决方案中删除主要方法后,您仍然可以调用sample.Problem。

,

虽然这违反了“习俗”,但您可以尝试做。但是main()类中存在Solution方法,因此您必须运行该方法。

在命令行中,您可以轻松地做到这一点:

javac Checker.java
java Solution

Solution.class将会正确生成。

但是,如果您使用的IDE并不十分熟悉,则试图告诉他们运行与他们刚刚编译的.class不同的.java文件时,可能会遇到困难。简而言之:将文件命名为Solution.java

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...