+ 2
Static question help pls
why i cant put static in the Animal method? public class Animal { static Animal() { System.out.println("Woof-Woof"); } } class MyClass { public static void main(String[ ] args) { Animal dog = new Animal(); Animal cat = new Animal(); } }
8 Réponses
0
@Oma Falk
could you explain why it can run now.im so confused...
public class Animal {
static void Animal() {
System.out.println("Woof-Woof");
}
}
class MyClass {
public static void main(String[ ] args) {
Animal dog = new Animal();
Animal cat = new Animal();
cat.Animal();
}
}
+ 3
First of all you're making the constructor of a class static which is a big error xD because any constructor of any class is instantiated therefore you can refer to it in a static context.
Second you're trying to call the constructor on an instance which, again, you can't do.
Finally you should make Animal abstract and then create the classes Dog and Cat and extend those from Animal. This means that a Dog and a Cat are Animals with more attributes, so in the class Animal you shall only place the attributes that are shared between all Animals, in this case Dogs and Cats.
Eg:
public abstract class Animal{
public abstract void talk();
}
public class Dog extends Animal{
@Override
public void talk(){
System.out.println("Woof Woof!");
}
}
+ 2
a static method belongs to a class not to an instance. The constuctor IS an instance method. It cant be static.
+ 2
@oyl could you copy this code to code playground
+ 2
it is not seen as constructor, otherwise the output would occur 2 times
0
@Oma Falk is it because static method belongs to the class.so no matter what object you created,it is linked to the class.so cat=class and dog=class
0
@André Martins
you say the code below is wrong but it still runs and gets the output.why?
public class Animal {
static void Animal() {
System.out.println("Woof-Woof");
}
}
class MyClass {
public static void main(String[ ] args) {
Animal dog = new Animal();
Animal cat = new Animal();
cat.Animal();
}
}
0
@Oma Falk
https://code.sololearn.com/citgBIeUO0Kn/?ref=app
you mean this?i still get wolf wolf for output