Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating objects in Java question

Tags:

java

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?

like image 967
Dr Hydralisk Avatar asked Feb 28 '10 08:02

Dr Hydralisk


1 Answers

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();
like image 59
Desintegr Avatar answered Sep 28 '22 22:09

Desintegr