Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

java, please explain why the first segment is right and why the second segment i

ID: 3749641 • Letter: J

Question

java, please explain why the first segment is right and why the second segment is wrong WITH DETAIL and example . Thank you.

Assume you have a class Square. Thislan instance variable, side that is protected and of type double. Write the class definition of a subclass of Square called FancySquare that has a method called getDiagonal. The getDiagonal method gets no arguments but returns the value of side multiplied by the square root of two. 16 of 16: Tue Sep 18 2018 21:27:31 GMT+1000 (Australian Eastern Stand SUBMIT 1 //CODE BELO S RIGHT 3 class Fancy5quare extends Square double getDiagonal0 return side Math.sqrt(2.8) 18 12 13 14 15 BELON IS WRONG public class FancySquare extends Square 17 18 19 public static double getbiagonal) return Square.side Math.sart(2.8) 23 24

Explanation / Answer

Here, the first segment is right, because the variable side is an instance variable of class Square, which is accessible in FancySquare class as it is of protected type. All the instance variables can only be accessed by a non static method in a non static way. That is the reason why second segment is wrong. In the second segment, the getDiagonal() method is static. Static methods can only access static variables or class variables, which is shared by all the objects of a class (no separate copies are made for individual objects). Also even if the getDiagonal() method was non static, this would not work because, it is trying to access the variable side using class name. Only static variables can be accessed by using class name.

Note that sqrt() is a static method of the class Math, so it can be accessed using class name Math instead of creating an object and using it to call the method. There is no problem in using / invoking static methods from a non-static method

If the side variable was static, then the first segment would be wrong, and the second would be right.

Check below for some valid and invalid usage of static / non static variables and methods in the above case

1. This is valid.

double getDiagonal(){

          return side*Math.sqrt(2);

}

2. This is Invalid because static methods cannot access non static variables

static double getDiagonal(){

          return side*Math.sqrt(2);

}

3. This is Invalid because non static variables cannot be accessed using class name

double getDiagonal(){

          return Square.side*Math.sqrt(2);

}

I hope everything is clear now. Just drop a comment if you have any doubts. Thank you!