In PHP, to create a new object you would do something like this, $dog = new Dog;
. But in Java you would do something like, Dog x = new Dog;
or Dog x;
. Could someone explain why you need to say the Dog class in front of the variable?
You need to precise the type because Java is a strong and static typed language.
If you declare x
as a Dog, it can only be a Dog or a subclass of Dog.
Another example :
public class Animal {
}
public class Dog extends Animal {
}
public class Cat extends Animal {
}
The following code is valid because x
is declared as Animal, it can be a Dog or a Cat, or any subclass of Animal :
Animal x;
x = new Dog();
x = new Cat();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With