[General boards] [Fall 2018 courses] [Summer 2018 courses] [Winter 2018 courses] [Older or newer terms]

Java Lookup Rules


#1

I’ve had different people tell me the look up rules for java, and I’ve tested them out. Is my understanding correct?

For instance methods, they look to the methods in the actual type of the object, then go up the parent tree. (overriding)

For instance variables, static variables, static methods, the variables/methods in the declared type of the object is looked to, then go up the parent tree


#2

Let class Student extend class Person. Then, the way to test the lookup rules is to create an instance that looks like this:

Person x = new Student();

Then try the toString method, to see which one it uses. It should use the toString from Student. But for everything else (static variables, static methods, instance variables), where both classes have one of the same name, it should use the one from Person.

I believe what you describe in your original post is the inheritance rules. If a class does not contain an instance method that exists in Object, java will work its way up the inheritance hierarchy, looking for the “lowest” version of the method to use.

Please try this out yourself. Do not take other people’s word for it. On the exam, we will be running the code from each of the questions to double-check our answers. Ultimately, if it works for you in IntelliJ, then it is correct.