Java 重写构造函数类

Java 重写构造函数类,java,constructor,overriding,Java,Constructor,Overriding,下面是我的代码。我不明白是什么错了。有人能给我指路吗 class State { static String country; static String capital; State() // Constructor { country = "America's"; capital = "Washington D.C"; } static void display() { System.out

下面是我的代码。我不明白是什么错了。有人能给我指路吗

class State {
    static String country;
    static String capital;

    State() // Constructor
    {
        country = "America's";
        capital = "Washington D.C";

    }

    static void display() {
        System.out.println(capital + " " + "is" + " " + country + " " + "capital.");

    }
}

class Place extends State // Method Overriding
{
    static void display() {
        System.out.println("Capital is Washington D.C.");
    }

    public static void main(String[] args) {

        State st = new State();
        Place pl = new Place();
        st.display();
        pl.display();
        st = pl;

    }
}
运行时,它显示为“错误:无法找到或加载主类状态$Place”

正如产出所需:“资本是华盛顿特区”,而不是(资本)+ “+”是“+”+国家+“+”资本。”)


您的
Place
类需要定义为
public

编辑:文件也必须命名为
Place.java

class State 
{
    static String country;
    static String capital;


    State()     //Constructor
    {
        country = "America's";
        capital = "Washington D.C";

    }

    static void display()
    {
        System.out.println(capital + " " + "is" + " " + country + " " +"capital." );

    }
}

主类

class Place extends State // Inheritance 
    static void display()
    {
        System.out.println("Capital is Washington D.C.");
    }
    public static void main(String[] args)
    {

        State st = new State();
        st.display(); // to print sub class method 
        display(); // to print same class method 
        //st = pl; No idea of this point ..

    }
}

这样做的目的是什么<代码>st=pl我可以使用它…显示“Capital is Washington D.C.”而不是(Capital++“是”++“country++”Capital。)您到底是如何运行此代码的?而且您不能覆盖静态方法。它们不是多态的,就像最终版本或私有版本一样。你为什么这么认为?您能更详细地解释一下吗?@TomK以及是什么让您认为main方法必须在公共类中?
main
method不需要在公共类中。此外,若顶级类不是公共类,那个么它不需要位于同名文件中,所以您的答案的两个方面都是错误的。我不知道是谁在不测试答案的情况下对答案进行了投票。@Pshemo使Place类main为我完美编译。这是我的输出:“华盛顿特区是美国的首都。首都华盛顿特区:“Java只允许main()方法在公共类中运行”不,它不允许。反例:“st.display();//to print sub class method”您可能指的是sup(super)类,因为
Place扩展State
st
属于
State
类型。换句话说,它与调用
State.display()
相同,因为
display
是静态方法。