About Question enthuware.ocajp.i.v7.2.1201 :

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
bluster
Posts: 60
Joined: Wed Apr 23, 2014 6:38 pm
Contact:

About Question enthuware.ocajp.i.v7.2.1201 :

Post by bluster »

This may be a distinction without consequence.. but: I was able to compile code changing the value of interface-defined variable TYPE in a class, after implementing the interface.

The difference from the scenario in the question is that I declared as int the variable TYPE in the class, as opposed to the code in the question, which reads "type = 1", not "int type = 1".

My point here is to ask if, in the question, could it be that the compiler was unhappy about the missing type "int" declaration in "type = 1"; as opposed to what I understood to be stated in the explanation - "...you cannot assign any value to 'type' outside the interface definition."

Sorry if confusing, that variable name in the question did not help to query a point about typing.. :)

The compiler-happy code is below, with the variable reassignment. Thanks for any clarification,


package sandbox;

interface I1 {
int TYPE = 1;
void m1();
}

class TestClass implements I1 {
int TYPE = 3; // >>>>>>>>>> this compiles fine!!

public void m1() {
System.out.println(TYPE);
}
}

public class SandBox {
public static void main(String[] args) {
TestClass tc = new TestClass();
tc.m1();

} // fim main
} // fim SandBox

admin
Site Admin
Posts: 10388
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: About Question enthuware.ocajp.i.v7.2.1201 :

Post by admin »

If you define int TYPE = 3; in the class, then that is an entirely different TYPE variable than the one defined in the interface. TYPE in class (the way you have defined it) is not final and you can change it. But TYPE, which is what the explanation is referring to, is final and cannot be assigned a value in the class.

HTH,
Paul.

bluster
Posts: 60
Joined: Wed Apr 23, 2014 6:38 pm
Contact:

Re: About Question enthuware.ocajp.i.v7.2.1201 :

Post by bluster »

Got it, thanks for the explanation, Paul.

A comment to help others who show up here. If one defines TYPE in the class as final, all still works: "final int TYPE = 3;" will compile well, in the code above, if you use it to replace the line defining TYPE in the class.

If you then print out both of the TYPE variables (from interface and class), it also works and print the two different values:
System.out.println(TYPE); // prints from class
System.out.println(I1.TYPE); // prints from interface

In the code above, you get 3 and 1.

Post Reply

Who is online

Users browsing this forum: No registered users and 6 guests