Override a constructor class

2019-03-03 18:58发布

问题:

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