Is this assigning bark with "woof"? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Is this assigning bark with "woof"?

public class Dog{ static void bark(){System.out.println("woof");} } thanks

15th Jul 2017, 10:33 AM
D_Stark
D_Stark - avatar
5 Answers
+ 6
This is a void function 'bark' which prints "woof" to the console. It is different from assigning a value to a variable. A function contains a block of code which is executed when the function is called.
15th Jul 2017, 10:50 AM
Hatsy Rei
Hatsy Rei - avatar
+ 3
Within the main itself you will have to instantiate dog object and make a call to bark function. Dog d = new Dog(); d.bark();
15th Jul 2017, 10:59 AM
Apoorva Shenoy Nayak
Apoorva Shenoy Nayak - avatar
+ 3
This would work too. I am not creating a separate object here but only calling the function bark from main public class Program { public static void main(String[] args) { bark(); } static void bark(){System.out.println("woof"); } }
15th Jul 2017, 11:12 AM
Apoorva Shenoy Nayak
Apoorva Shenoy Nayak - avatar
0
how come i can call it from main without it being assigned using Dog.bark();?
15th Jul 2017, 10:57 AM
D_Stark
D_Stark - avatar
0
@ apoorva i can do this without having to instantiate dog object i can just do dog.bark(); and it works?? would doing it your way allow me to change bark(); to somthing else if i was going to create another animal?
15th Jul 2017, 11:05 AM
D_Stark
D_Stark - avatar