覆盖构造函数类

时间:2017-02-23 14:56:01

标签: java constructor method-overriding

以下是我的代码。我没有得到什么是错误。任何人都可以指导。

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;

    }
}

运行时显示为“错误:无法找到或加载主类State $ Place”

  

由于产出需要:“资本是华盛顿D.C.”而不是(资本+   “”+“是”+“”+国家+“”+“资本。”)

2 个答案:

答案 0 :(得分:0)

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 ..

    }
}

答案 1 :(得分:-1)

您的Place课程需要定义为public

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