Error "Can not make static reference to the non-static faithful

0

I'm doing an exercise with a class Carro and subclasses Familiar Citadino and Jipe ... Only when doing a class Testabuzinar1 that instantiates each of the subclasses and then calls the method honk (which is in class Carro ) and an error appears to me

  

Can not make astatic reference to the non-static field ...

Follow the code of the Testa buzina 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();

    }

}
    
asked by anonymous 08.04.2017 / 16:13

1 answer

2

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

If it is even necessary that they be class fields add static so that the fields can be accessed directly in 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 simply create an instance of class 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 was well remembered by @Anderson , there is a simpler solution, which is to make the local fields within 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?

    
08.04.2017 / 16:18