+ 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(); } }

20th Oct 2017, 6:12 AM
oyl
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(); } }
20th Oct 2017, 6:40 AM
oyl
+ 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!"); } }
20th Oct 2017, 7:31 AM
Chriptus13
Chriptus13 - avatar
+ 2
a static method belongs to a class not to an instance. The constuctor IS an instance method. It cant be static.
20th Oct 2017, 6:32 AM
Oma Falk
Oma Falk - avatar
+ 2
@oyl could you copy this code to code playground
20th Oct 2017, 2:09 PM
Oma Falk
Oma Falk - avatar
+ 2
it is not seen as constructor, otherwise the output would occur 2 times
20th Oct 2017, 3:03 PM
Oma Falk
Oma Falk - avatar
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
20th Oct 2017, 6:47 AM
oyl
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(); } }
20th Oct 2017, 1:56 PM
oyl
0
@Oma Falk https://code.sololearn.com/citgBIeUO0Kn/?ref=app you mean this?i still get wolf wolf for output
20th Oct 2017, 2:15 PM
oyl