Error "Cannot make Static Reference to the non-static faithful

Asked

Viewed 1,700 times

0

I’m doing a class exercise Carro and subclasses Familiar Citadino and Jipe... Only by making a class Testabuzinar1 which instantiates each of the subclasses and then calls the horn method (which is in the class Carro) and I get a mistake

Cannot make Astatic Ference to the non-static field...

Follow the code of the Forehead horn class

public class TestaBuzinar1 {
    public Citadino citadino = new Citadino(); //ou Citadino citadino=new citadino()
    public Familiar familiar = new Familiar();
    public Jipe jipe = new Jipe();

    public static void main(String[] args) {

        citadino.buzinar();
        familiar.buzinar();

    }

}

1 answer

2


The error is clear, you are trying to access non-static fields inside the main, which is static.

If you really need them to be add class fields static so that the fields can be accessed directly on main:

public class TestaBuzinar1 {
    public static Citadino citadino = new Citadino(); //ou Citadino citadino=new citadino()
    public static Familiar familiar = new Familiar();
    public static Jipe jipe = new Jipe();

    public static void main(String[] args) {

        citadino.buzinar();
        familiar.buzinar();

    }

}

Or you can also simply create a class instance TestaBuzinar1:

public class TestaBuzinar1 {
    public Citadino citadino = new Citadino(); //ou Citadino citadino=new citadino()
    public Familiar familiar = new Familiar();
    public Jipe jipe = new Jipe();

    public static void main(String[] args) {

        TestaBuzinar1 testb = new TestaBuzinar1();    
        testb.citadino.buzinar();
        testb.familiar.buzinar();

    }

}

As well remembered by @Anderson, there is a simpler solution, which is to make the local fields within the main:

public class TestaBuzinar1 {

    public static void main(String[] args) {

        Citadino citadino = new Citadino(); //ou Citadino citadino=new citadino()
        Familiar familiar = new Familiar();
        Jipe jipe = new Jipe();

        citadino.buzinar();
        familiar.buzinar();

    }

}

Recommended reading:

What is the use of a static or final variable in java?

  • Or includes instances of classes in the method main, making them local.

  • @Andersoncarloswoss had forgotten that possibility

  • Thanks for your help

Browser other questions tagged

You are not signed in. Login or sign up in order to post.