Y is java so hard? =[ so many questions... Very few answers... | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Y is java so hard? =[ so many questions... Very few answers...

1. Void I think that void is a method. But how does it contribute to the main? Also what are () in code? 2. Getters and setters I am really confused between getters and setters. I think that getters return things, but what are setters? public class Vehicle { private String color; public String getColor() { return color; } public void setColor(String c) { this.color = c; Also in this code there is a 'String c' while in the getColor there isn't. Y? And what does the '.' do?!

1st Mar 2017, 7:21 PM
PaperGami T.
PaperGami T. - avatar
8 Answers
+ 5
In Java you HAVE TO declare the return type of the method. If it doesn't return value, then you have to write void.
1st Mar 2017, 7:39 PM
Tamás Barta
Tamás Barta - avatar
+ 3
void can be used as a special "return type" of a method. It means that the method doesn't return anything. when you see foo() in a Java code it means that you call the foo method. In this statement () means method invocation. If the method has parameters you can write them inside brackets: foo(1, 2)
1st Mar 2017, 7:35 PM
Tamás Barta
Tamás Barta - avatar
+ 3
Using . you can access an attribute or method of an object. For example: obj.color
1st Mar 2017, 7:38 PM
Tamás Barta
Tamás Barta - avatar
+ 3
When you declare a method you declare its parameters, for example: int add(int a, int b) { return a+ b; } So you write the code what you want to do with the parameters. You can call this method this way: add(1, 2); it will return 3
1st Mar 2017, 7:41 PM
Tamás Barta
Tamás Barta - avatar
+ 3
Implementation of the horn method prints this value. So when you call horn () it will be printed out. The horn method doesn't return anything. Returned value won't be printed out unless you print it explicitly.
1st Mar 2017, 7:45 PM
Tamás Barta
Tamás Barta - avatar
+ 2
Then what's the point of a void if it doesn't do anything and doesn't return? When u put numbers in the (), what can we do with the numbers?
1st Mar 2017, 7:37 PM
PaperGami T.
PaperGami T. - avatar
+ 2
public class Vehicle { int maxSpeed; int wheels; String color; double fuelCapacity; void horn() { System.out.println("Beep!"); } } class MyClass { public static void main(String[ ] args) { Vehicle v1 = new Vehicle(); Vehicle v2 = new Vehicle(); v1.color = "red"; v2.horn(); } } But if horn is voided, then why does the code out print Beep?
1st Mar 2017, 7:42 PM
PaperGami T.
PaperGami T. - avatar
+ 2
Thanks!
1st Mar 2017, 7:47 PM
PaperGami T.
PaperGami T. - avatar