Q:

Is It Accepted Or Legal To Do this

I have a method in a class say
// super class
public class Car{

    public void printMe(Car c){
          if(c instanceof BMW){
            Utility.printString("Bmw");
      }else if(em instanceof VOLVO){
            Utility.printString("Volvo");
      }else if(em instanceof AUDI){
            Utility.printString("Audi");
      }else {
            Utility.printString("Kia");
        }
    }

// sub classes 

public class Bmw extends Car{

}

public class Volvo extends Car{
}

public class Audi extends Car{
}

public class Kia extends Car{
}

}

Now here i have a different class that loops through a list of Cars and print the correct statement according to the type of the Car
public class AccessCars{
   ArrayLists<Car> carsList = listOfcars();

for(Car car: carsList){
   car.PrintMe(car);   
}

}

In the loop above i call the printMe(Car c) method on car en give car as an argument. Is is legal to do that? And if not, what is the best way of doing it?
thanks for your answer

A:

a better way will be:
public abstract  class Car {
public abstract void printMe();
}
public class Audi {
@Override
public void printMe() {
Utility.printString("Audi");
}

 this is the OOP way to do it - using polymorphism
 note that Car is implicit argument for printMe()

A:

I would advise against polymorphism in this case -- every class prints out a string in the same way. The behavior is constant -- only the value printed varies. As such, the correct approach (IMO) is a variable that's printed out by printMe, and each derived class just initializes the variable appropriately.

