+ 1

why can't you overload variables?

(1) I tried to make 2 variables in java: protected int strength; protected double strength; (2) I see that strength has already been declared, but how come it can be done for something like: int max(int x, int y) int max(double x, double y) (3) one last thing: would it be considered overriding or overloading, or does it simply not apply at all (my guess is overloading because its the same variable name but with a different variable type) (4) can you only override methods? In a more specific explanation, if you can:) a lot of questions popped up while writing this, but answers are so appreciated thank you so much sololearn ^.^

30th Mar 2019, 11:10 PM
koala 🐨
koala 🐨 - avatar
2 Answers
+ 3
1.compiler gets confused.it doesn't know which variable you want to access.so Java doesn't support variable overriding in same class.but you can overload variables from subclass.now,the execution happens based on reference type.if you declared a subclass reference variable, then you can access subclass variable. 2.you have mentioned example of method overloading for max() method.however,you can have same name,same type and same parameters of a method(method overriding). control goes to a method based on object type.if you create a reference variable of base class,but object of subclass,then method from subclass is chosen.
31st Mar 2019, 1:00 AM
Home Number
Home Number - avatar
+ 2
// Overloading is only for methods. // If a class has multiple methods // with same name but different parameters // it is known as method overloading. // A small example // This make us able to add two integers. static int aMethod(int a, int b){ return a+b; } // But we also want the same method to take in // the type double, so the only thing we change // here is the return type, and in this method // i changed variable a,b to c,d, but you dont need // to change it, you can use same variables. static double aMethod(double c, double d){ return c+d; } public static void main(String[] args){ System.out.println(myClass.aMethod(33,44)); System.out.println(myClass.aMethod(66.55,88.99)); } You can read this about overriding, it will help you👍 https://www.javatpoint.com/method-overriding-in-java
31st Mar 2019, 1:01 AM
JavaBobbo
JavaBobbo - avatar