+ 4
What is special about objects created this way?
Lets say I have a superclass A, and a subclass B that inherits from A. Now what is the purpose of creating an object this way? A test = new B (); Or in other words superclass = new subclass? Grateful for any answers!
4 Respuestas
+ 5
I think you must to check Casting and Downcasting in Java Sololearn
https://www.sololearn.com/learn/Java/2168/
https://www.sololearn.com/learn/Java/2169/
+ 3
There are some good uses for this -
Take the Java Collections API. I might create a method that takes in a Set and does some operation. I write
public void operation(Set mySet) {
// code
}
If I had instead used a HashSet I would have access to any methods in Hashsets that Set doesn't, but that now restricts me to only using HashSet. If, later on, I wanted to switch to a TreeSet, it would be more difficult. However with the Set interface used as the type, I can currently pass in any Set I want. Coding to an interface or parent/base class keeps the code more general, and further separated from implementation.
There is also a 'strategy pattern' that takes advantage of this. I used it in one of my codes, which is commented:
https://code.sololearn.com/cop6od6LxalY/?ref=app
for example, look at the Token interface and classes that implement it (the code is actually executed near the top of the code)
0
I hope this code helps explaining :
public class Animal {
void sound() {
System.out.println("Animal sound");
}
}
public class dogs extends Animal {
void sound() {
System.out.println("Woof-Woof");
}
}
public class cats extends Animal {
void sound() {
System.out.println("Meao-Meao");
}
}
class MyClass {
public static void main(String[ ] args) {
Animal animal= new Animal();
animal.sound();
Animal dog= new dogs();
dog.sound();
Animal cat= new cats();
cat.sound();
}
}