If i have a superclass called Animal, and subclasses called Cat, Dog, Bird.
If I read an array of Animals, and want to access a Cat specific method called meow(), how do i do this?
I know i can use getClass() to find out the Animal's subclass, but how do i use to create a reference to access meow()
If you are using an array of animals, you need to check whether the object you are working with is an instance of Cat class, this can be achieved by using the instanceof operator. Then we can use the downcasting operator to convert the Animal to a Cat and then call the meow() method.
if(animal instanceof Cat){
(Cat)animal.meow()
}
With an array
Animal [] animals = [];
foreach(Animal animal: animals){
//do something
if(animal instanceof Cat){
(Cat)animal.meow()
}
}
You can cast to Cat
if (animal.getClass().getName().equals('Cat')) {
((Cat)animal).meow();
}
Or you could use instanceof.
Both of those solutions are ugly, and Java was not designed to be used this way. Instead, you should create a .speak method for the animals that could call Cat.meow internally.
Like this ...
if (animal.getClass().getName().equals('Cat')) {
((Cat)animal).meow();
}
or
if (animal instanceof Cat) {
((Cat)animal).meow();
}
Once you found out the subclass you want to use, you can cast it. In your case it would be
((Cat)animals[index]).meow();
Related
what I have is a list of Dog objects, in the objects there contains a value that is a Boolean to show whether the dog as completed a training or not. What im trying to do is iterate over the list and only return Dog() objects that have completed training, for instance if their are 12 dogs, and only 3 have completed training, the loop should only print those objects.
else if (input == 1) {
for (int i = 0; i < 12; ++i) {
//Create a temporary value to hold the object.
Object tempHold = dogKennel.getAnimal(i);
//If animal has not graduated, skip, else print.
if (!(tempHold.getGraduation())) {
continue;
}
else {
System.out.println(dogKennel);
}
}
getAnimal(i) returns the object at int i
the method .getGraduation is defined and does return a Boolean however the compiler doesnt want to recognize temp value as is, and doesnt go beyond that value. the compiler keeps suggesting to cast tempHold, but even if I do, it doesnt work.
i feel like it would work if i could get it to compile, as the object that is returned would have a getGraduation() method (it is defined for the super class of the animal.)
however the compiler doesn't want to recognize temp value as is, ...the compiler keeps suggesting to cast tempHold, but even if I do, it doesn't work.
The compiler is telling you two things:
An Object is NOT a Dog (the opposite is true. A Dog is an Object).
class Object does not have method isGraduated() defined for them.
To fix this, you can cast Object to Dog:
Dog tempHold = (Dog)dogKennel.getAnimal(i);
Now that we have a Dog, we can safely invoke isGraduated() on it. But the problem is we canNOT be sure that we have a Dog. We may as well have a Cat if we get the Animal from another kennel. In that case, you will get a ClassCastException which tells you that Cats cannot be cast as Dogs.
To avoid getting run time exceptions, you can add a check:
Object tempHold = dogKennel.getAnimal(i);
if(tempHold instanceof Dog) {
Dog dog = (Dog)tempHold;
System.out.println(dog.isGraduated());
}
The instanceof check fixes the problem.
There are ways to avoid this run time check altogether. One would be to create an interface:
public interface CanGraduate {
default boolean isGraduated() {
return false;
};
}
Then make all Animals implement this interface:
public abstract class Animal implements CanGraduate {
//Behavior common among all animals
}
You can now freely add new animal types and be assured that you can safely invoke isGraduated() on them and get a false value as long as they inherit from the above Animal class.
For dogs, isGraduated() is supposed to be more meaningful. So you can override it in their case:
public class Dog extends Animal {
private boolean _graduated = true;
#Override
public boolean isGraduated() {
return _graduated; //or some complex logic that determines graduation
}
}
With this structure, you no longer need to worry about invoking the method on any kind of Animal.
As an example, let us see some driver code:
public class Main {
public static void main(String[] args) {
Dog dog1 = new Dog();
Dog dog2 = new Dog();
Cat cat1 = new Cat();
Cat cat2 = new Cat();
List<Animal> dogKennel = List.of(dog1, dog2);
List<Animal> catKennel = List.of(cat1, cat2);
for(Animal x : catKennel) {
System.out.println(x.isGraduated());
}
}
}
The program will simply output false since Cats can never graduate. If the kennel contained Dogs, it would output the actual graduation status of the dog.
Like the others have said, the getGraduation() method is only defined presumably in the Dog class. This means that the method can only be called on Objects with the type Dog. To define a variable with type Dog you can do Dog temphold = *whatever*. The reason it wants you to cast is because Object is a supertype of Dog. If you'd like to read more about casting you can here: https://javarevisited.blogspot.com/2012/12/what-is-type-casting-in-java-class-interface-example.html
Basically, all you have to do is a cast to convert the object
if (!(((Dog)tempHold).getGraduation()))
{
continue;
}
this casting tells the compiler that even though tempHold is an object of the Object class it also is an object of the Dog class and should have all of its properties
If you want to filter the list for just ones with a certain condition, the most common way to do that these days is with the Stream::filter method.
It would look like this:
List<Dog> completedTraining =
dogKennel
.stream()
.filter(
dog -> !dog.getGraduation()
)
.collect(
Collectors.toList()
)
;
class Animal{
public void findAnimal(){
System.out.println("Animal class");
}
public void sayBye(){
System.out.println("Good bye");
}
}
class Dog extends Animal{
public void findAnimal(){
System.out.println("Dog class");
}
}
Given the inheritance above ,it is understood that a reference of Animal can refer to an object of Dog
Animal animal=new Dog();
As a Dog object can perform everything an Animal can do like in above case a Dog also have sayBye and findAnimal methods.
But why it is allowed to downcast an Animal object to a Dog object which serves no purpose and fails at runtime.
Dog dog=(Dog)new Animal(); // fails at runtime but complies.
Dog dog=(Dog)animal;
The above statement look logical as the animal reference is pointing to a Dog object.
This sort of casting is allowed for situations when you get an object of a superclass from outside code, e.g. as a parameter to your method, and then you need to call methods specific to a subclass.
This is not a good practice, but in some rare situations you are forced to do things like that, so the language allows it:
void sound(Animal animal) {
if (animal instanceof Dog) {
Dog dog = (Dog)animal();
dog.bark();
}
if (animal instanceof Cat) {
Cat cat = (Cat)animal();
cat.meow();
}
}
why it is allowed to compile Dog dog=(Dog) new Animal()
Because compiler designers decided to not detect this error at compile time. They verified that the expression being cast to Dog is of type that is a superclass of Dog, and allowed the expression to compile. They could go further and check that the expression will always result in an exception, but that would require an additional effort for very little improvement in user experience with the language.
Because you need it sometimes.
Especially when Java did not yet have generics (Java 1.4 and older), you almost always needed to cast when you got for example an object out of a collection.
// No generics, you don't know what kinds of objects are in this list
List list = new ArrayList();
list.add(new Dog());
// Need to cast because the return type of list.get() is Object
Dog dog = (Dog)list.get(0);
Since we have generics since Java 5, the need for casting is greatly reduced.
You should try to avoid casting in your code as much as possible. A cast is a way to deliberately switch off the compiler's type checking - in general you don't want to do that, you want to make use of the compiler's checking instead of circumventing it. So, if you have code where you need to cast, think a bit further to see if you can write it without the cast.
You need that capability to access an earlier cast object as its original type.
For example, if you cast a Dog to an Animal to pass it to a generic processor, you may later need to cast it back to a Dog to perform specific methods.
The developer is responsible to make sure the type is compatible - and when it is there will be no error. Some pseudo code:
public void example(Animal foo){
if( ...condition... ) ((Dog)foo).bark();
else if( ...other condition... ) ((Cat)foo).meow();
}
Since the introduction of generics, this is less commonly used, but there are still cases for it. The developer is solely responsible for guaranteeing the type is right if you don't want an error.
case 1 -
Here we use loose coupling.
Animal animal = getSomeDog(),
Dog dog = (Dog) animal; // this is allowed because animal could reference a dog
case 2
Here we you use tight coupling.
Animal animal = new Animal();
Dog dog = (Dog) animal; // this will fail at runtime, because animal doesn't reference a Dog
We use Downcasting when there is possibility to succeed at run time
so case 1 has possibility to succeed at runtime over case 2
Down casting is considered as a bad Object Oriented practice. It must be avoided to as much extent as possible.
Java still has it and your question is a good question as why Java allows Down-casting.
Suppose a case below.
public interface List{
public boolean add(Object e);
public boolean remove(Object o);
}
public class ArrayList implements List{
// Extra method present in the ArrayList and not in the parent Interface
public Object[] toArray() {
// returns array of the objects
return Arrays.copyOf(elementData, size);
}
#Override
public boolean add(Object e){
// add e to the ArrayList Underlying array
}
#Override
public boolean remove(Object o){
// remove o from the ArrayList Underlying array
}
}
A good Object oriented practice is to Code for Interfaces. But often there are methods defined in the concrete implementations which we need to call. I read an comment from some one and I quote it in my words.
Know the Rules, in case you need to break them Do break them Knowingly and take care so as to prevent from any adverse effect.
Below is an example where we need to do the Down-casting. The example of down-casting in your question is to teach what is down-casting, below is real life example.
public void processList(List items){
items.add( new Object() );
items.add( new Object() );
processAsPerTypeOfList(items);
}
public void processAsPerTypeOfList( List items ){
if( items instanceof ArrayList){
Object[] itemArray = ((ArrayList)items).toArray();// DOWNCASTING
// Process itemArray
}
}
For more reference you can also see a related question : Why Java needs explicit downcasting?
I've made an Animal superclass, Shark and Whale subclasses. What would I use to print out just the Shark objects from this arraylist?
Driver:
import java.util.ArrayList;
public class Creator {
public static void main(String[] args){
ArrayList<Animal> obj = new ArrayList<Animal>();
obj.add(new Shark("James"));
obj.add(new Shark("Mike"));
obj.add(new Whale("Steve"));
obj.add(new Whale("Tommy"));
for (Animal a: obj){
System.out.println(a.getName());
}
}
}
You can use the instanceof to check for specific subclass from the list of superclass Animal
for (Animal a: obj){
if(a instanceof Shark)
System.out.println(a.getName());
}
Simple variant is just using instanceof. You can also create a getType() method in the base class, that will return, for example, a enum object or other entity to define the species in subclasses.
Use instanceof.
From JLS 15.20.2. Type Comparison Operator instanceof
At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising a ClassCastException. Otherwise the result is false.
Ex: Iterate over your ArrayList
if(yourObject instanceof Shark){
System.out.println(yourObject.getName());
}
I have many sub-classes implementing the superclass Animal (Dog, Cat, Mouse, etc)
So I do:
Animal[] arrayOfAnimals = new Animal[100];
I put in it Dog,Cat etc objects.
When I get something from it I do
If(arrayOfAnimals[1] instanceof Dog) {
((Dog)(arrayOfAnimals[1])).speak();
}
else if(arrayOfAnimals[1] instanceof Cat) {
((Cat)(arrayOfAnimals[1])).speak();
}
Because I need to know if that Animal is a Cat or a Dog because,for example, each one speaks differently.
Now assuming I have many subclasses of Animals, I will consecutively get many "else if..."
My question is: Is there a way to avoid this? I have already tried using an interface (Animal -> interface, Dog,Cat etc implementing animal), but in my project an array has to be cloneable, and you can't clone an array "Animal [] arrayOfAnimals" if Animal is an interface (objects inside that array will not be cloned)
Because i need to know if that Animal is a Cat or a Dog because,for example, each one speaks differently.
That sounds like it's an implementation detail - if every animal can speak in some form, you should put the speak() method into Animal as an abstract method. Each subclass will then override it to provide the implementation. Then you can just use
arrayOfAnimals[1].speak();
... and polymorphism will take care of using the right implementation.
You can clone an array of an interface type, btw:
interface Foo {
}
class FooImpl implements Foo {
}
public class Test {
public static void main(String[] args) {
Foo[] foos = { new FooImpl() };
Foo[] clone = (Foo[]) foos.clone();
System.out.println(foos[0] == clone[0]); // true
}
}
Note that regardless of the type involved, calling clone() on array won't clone each element - the new array will contain the same references as the old array. It's a shallow copy. If you want to do that, you'll have to code it yourself (or find a third party library).
Why don't you move speak() to the superclass and let the subclasses override it?
I'm sure this is incredibly common with as OOP centered as Java is. In java is there a way to make a base type variable that accepts all inherited subtypes? Like if I have;
class Mammal {...}
class Dog extends Mammal {...}
class Cat extends Mammal {...}
class ABC {
private Mammal x;
ABC() {
this.x = new Dog();
-or-
this.x = new Cat();
}
}
I need the variable to be able to accept any extended version too, but not in specific one extended kind.
There are some ways that I know, but don't want to use. I could make an attribute for each subtype, then only have the one attribute actually used. Make an array and shove it in there.
Any other ideas or a way to get a "base class" type variable?
Ok since I know using polymorphic duck typing isn't a great idea in Java, but since I don't think I can avoid it. Is the only way to use subclass methods dynamically to re assign a casted version of the varible ie, I get an error with this;
Mammal x;
x = new Dog();
System.out.println(x.getClass());
x.breath();
if (x instanceof Dog) {
x.bark();
} else if (x instanceof Cat) {
x.meow();
}
Saying symbol not found, however this works;
Mammal x;
x = new Dog();
System.out.println(x.getClass());
x.breath();
if (x instanceof Dog) {
Dog d = (Dog) x;
d.bark();
} else if (x instanceof Cat) {
Cat c = (Cat) x;
c.meow();
}
That last one the only way to do it?
If you have the following:
class Mammal {...}
class Dog extends Mammal {...}
class Cat extends Mammal {...}
Then Dog is a subtype of Mammal. Cat is also a subtype of Mammal. This type polymorphism does in fact allow you to do the following:
Mammal x;
x = new Dog(); // fine!
x = new Cat(); // also fine!
If in fact later there's the following:
class Platypus extends Mammal {...} // yes it's true!
Then you can also do:
x = new Platypus(); // fine!
This polymorphic subtyping relationship is one of the basic tenets of object-oriented programming.
See also
Java Tutorials/Object-Oriented Programming Concepts
Wikipedia/Polymorphism in object-oriented programming
Subtype polymorphism, almost universally called just polymorphism in the context of object-oriented programming, is the ability of one type, A, to appear as and be used like another type, B
On instanceof type comparison operator
Suppose we have the following:
class Mammal { void lactate(); }
class Dog extends Mammal { void bark(); }
class Cat extends Mammal { void meow(); }
Then you can use instanceof type comparison operator (ยง15.20.2) to do something like this:
Mammal x = ...;
if (x instanceof Dog) {
Dog d = (Dog) x;
d.bark();
} else if (x instanceof Cat) {
Cat c = (Cat) x;
c.meow();
}
if (x != null) {
x.lactate();
}
There are also ways to do this without if-else; this is just given as a simple example.
Note that with appropriate design, you may be able to avoid some of these kinds of subtype differentiation logic. If Mammal has a makeSomeNoise() method, for example, you can simply call x.makeSomeNoise().
Related questions
When should I use the Visitor Design Pattern? - sometimes used to simulate double dispatch
On reflection
If you must deal with new types not known at compile-time, then you can resort to reflection. Note that for general applications, there are almost always much better alternatives than reflection.
See also
Java Technical Articles/Advanced Language Topics/Reflection
Effective Java 2nd Edition, Item 53: Prefer interfaces to reflection