Override a constructor class

ぐ巨炮叔叔 提交于 2019-12-20 05:41:20

问题


Below is my code. I am not getting what is the mistake. Can anyone be able to guide.

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;

    }
}

While running it displays as "Error: Could not find or load main class State$Place"

As the output needs: "Capital is Washington D.C." instead of (capital + " " + "is" + " " + country + " " +"capital.")


回答1:


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." );

    }
}

Main class

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

    }
}



回答2:


Your Place class needs to be defined as public.

Edit: The file also must be named Place.java



来源:https://stackoverflow.com/questions/42419185/override-a-constructor-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!