Diagnostic Quiz
Problems
Q2. More on private
private
The first two options are relatively easy to analyze, the problem lies in the third option b.y=1 and this is valid because foo belongs to class B, and thus has access to y of any instance of B.
Private fields are accessible to all methods within the same class, regardless of which instance is being accessed.
Q8. Subtype and Inheritance
Given the following code,
The inheritance relationship we can get is (Here, let's denote as " is the parent of .)
Then from the inheritance relationship, we should get this subtype relationship . And then use the basic knowledge of combinatorics, we know there will be 3 possible answers.
Q11. this and class method
this and class methodGiven the following code,
Firstly, we notice that the method getNumber() is static. According to our learning in class method, we should deduce that the getNumber() method is associated to the class, instead of any instance from the class.
Also, in our learning, we know that a class method cannot access its instance fields or call other of its instance methods, and one corollory of this is that the keyword this is also not allowed in a class method (This is also covered in the lecture notes).
Q12. main() method
main() methodSame as we have seen in the lecture notes, the main() method must be declared as the following:
Q13. Method Signature and Descriptor
For this problem, refer back to the lecture ntoes about method signature and method descriptor.
Q15. Overriding and Overloading
I will leave it when I learn Overloading.
Tips
Private fields are accessible to all methods within the same class, regardless of which instance is being accessed.
Suppose we have two classes and , if inherits from , then we can say is the subtype of or .
A class method (method with the keyword
static) cannot access its instance fields or call other of its instance methods, and one corollory of this is that the keywordthisis also not allowed in a class method. Otherwise, a compilation-error will be generated.Include the method signature and method descriptor in the cheatsheet!
Last updated