0

I´m getting cannot find symbol error in my code (symbol: method setAr(boolean)).

Here is my Main.java file:

class Vehicle {
    protected int marchs;
    protected int rode;
    public void xydar(int km) { System.out.print("\nxydei "+ km +" km!"); }
}
class Car extends Vehicle {
    public Car() { this.rode = 4; }
    public void xydar(int km) {
    super.xydar(km);
    System.out.println(" Estou de car!");
    }
}
class CarLux extends Car {
    private boolean ar;
    public CarLux() { this.ar = true; }
    public void setAr(boolean newAr) { this.ar = newAr; }
    public void xydar(int km) {
        super.xydar(km);
        if (this.ar)
        System.out.println(" ON!");
        else System.out.println(" OFF!");
    }
}
public class Main {
public static void main(String []args) {
    Vehicle moto = new Vehicle();
    moto.xydar(90);
    Vehicle car1 = new Car();
    car1.xydar(100);
    Vehicle car2 = new CarLux();
    car2.xydar(400);
    car2.setAr(false);
    car2.xydar(400);
    }
}

How can I call setAr() method correctly? Can anyone help me? I´m new to Java. Thanks in advance.

eightShirt
  • 1,457
  • 2
  • 15
  • 29
  • Possible duplicate of [What does a "Cannot find symbol" compilation error mean?](http://stackoverflow.com/questions/25706216/what-does-a-cannot-find-symbol-compilation-error-mean) – Raedwald Feb 26 '16 at 20:12

2 Answers2

4

You need to declare car2 as a CarLux, not a Vehicle.

CarLux car2 = new CarLux();

That's because your setAr() method is defined on CarLux. car2 is currently held in a variable of type Vehicle, so when you call a method of car2 only the methods declared by Vehicle will be available.

Mark Peters
  • 80,126
  • 17
  • 159
  • 190
  • Unless I'm missing something, he does. Edit: derpy derpy derpy, types are your friend – Timr Apr 26 '14 at 05:41
  • 1
    @Timr: He's *instantiating* a `CarLux`, but the object isn't a concrete instance of a `CarLux`. – Makoto Apr 26 '14 at 05:42
  • I understand car2 is a CarLux, but why this code works to xydar method and calls the xydar from the correct subclass? Just because are the xydar method on Vehicle class? And a CarLux is a Vehicle, right? That's my headache. – eightShirt Apr 26 '14 at 05:51
  • @eightShirt: Correct. `xydar` is *declared* in `Vehicle`. Subclasses may override the *implementation*, which `CarLux` has done. The [Java Tutorial for Polymorphism](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) will help you explore this topic. – Mark Peters Apr 26 '14 at 15:51
0

You can call setAr method only through an object of type CarLux because this is method of CarLux not Vehicle so you have to cast car2 as CarLux then call method like this -

((CarLux)car2).setAr(false);
Ravi Kumar
  • 993
  • 1
  • 12
  • 37