Nested methods | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Nested methods

Errors tell me that I cannot create methods inside methods, is that true? I want something like as follows: class Vehicle { private String color; public String SetAndGetColor(String c){ void setColor(){ this.color = c; } String getColor() { return this.color; } } public class Program { public static void main(String[]args) { System.out.println(SetAndGetColor("cyan")); } } compiler doesn't recognize inside methods at all as methods

28th Mar 2017, 6:29 AM
Alex Snaidars
Alex Snaidars - avatar
1 Answer
+ 7
Yeah, you can't create methods inside methods, but you can create all the methods in the class all call the method from another method. String SetAndGetColor(String c){ setColor(c); return getColor(); //or you can just return color; } void setColor(String c){ this.color = c; } String getColor(){ return color; }
28th Mar 2017, 8:53 AM
Heng Jun Xi
Heng Jun Xi - avatar