+ 1

Class, void method()

int method(); string method(); void method(); ect... does the method have to have a return type in class? im trying to inderstand void method() in class i notice it always seems to have a output in the head which you can call from the body... does it always have to be like this?

18th Jul 2017, 9:13 AM
D_Stark
D_Stark - avatar
3 ответов
+ 2
It is necessary to always have a return type on a method. There are some exceptions, such as constructors. void is a return type. It means this method does not return a value. If you want, you can still use the return statement to change the flow of the program. Example/ boolean isDead; void attack(){ if(isDead) return; // return is used move(); fight(); } But what does it mean to 'not return a value'? Compare these methods: void add(int x, int y){ int c = x + y; } int add(int x, int y){ return x + y; } int d = add(5, 4); If this were for the int method, this would be fine. Since the value returned would be 5 + 4. In other words, I'm assigning d to the value of add(5, 4) If this were to be for the void method however, it would result in an error. As void does not return a value. What would it mean to assign the value of a variable to a method that has no value? I would need to write: add(5, 4); To change the flow of the program and to do whatever operations in that method I want with c.
18th Jul 2017, 2:09 PM
Rrestoring faith
Rrestoring faith - avatar
+ 2
Hey David! How are you today? No, not necessary to always have a return type. You can print the values to command prompt. void somemethod() print("value "+x );
18th Jul 2017, 9:31 AM
Apoorva Shenoy Nayak
Apoorva Shenoy Nayak - avatar
0
faith that was explained really well thanks
18th Jul 2017, 4:34 PM
D_Stark
D_Stark - avatar