overriding field | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
9th Apr 2021, 4:34 PM
VṢtēphen
VṢtēphen - avatar
5 Answers
+ 1
I can see you are trying anonymous classes, though you don't even have a method to override. Takes this as a simple example: class Machine { public int Age(int age) { return age; } } class Program { public static void main(String[ ] args) { Machine m = new Machine() { @Override public int Age(int age) { return age + 1; } }; System.out.println (m.Age(10)); } }
9th Apr 2021, 5:37 PM
Maher Al Dayekh
Maher Al Dayekh - avatar
+ 1
I can override method
9th Apr 2021, 6:56 PM
VṢtēphen
VṢtēphen - avatar
+ 1
Am asking if we can override field
9th Apr 2021, 6:56 PM
VṢtēphen
VṢtēphen - avatar
+ 1
No, not the way you are trying. This works however: public class Vehicle { static int maxSpeed = 5; String color; } class MyClass { public static void main(String[ ] args) { Vehicle v1 = new Vehicle(); v1.color = "red"; System.out.println(v1.color); v1.maxSpeed = 10; System.out.println(v1.maxSpeed); } }
9th Apr 2021, 7:08 PM
Maher Al Dayekh
Maher Al Dayekh - avatar
+ 1
Thanks...
9th Apr 2021, 9:01 PM
VṢtēphen
VṢtēphen - avatar