Java OCA OCP Practice Question 1199

Question

What is a possible output of the following application?

package mypkg; //from   w  ww  .j av a 2  s  .  c  o m
public class Main { 
        private final Object contents; 
        protected Object getContents() { 
           return contents; 
        } 
        protected void setContents(Object contents) { 
           this.contents = contents; 
        } 
        public void showPresent() { 
           System.out.print("Your v: "+contents); 
        } 
        public static void main(String[] treats) { 
           Main v = new Main(); 
           v.setContents(v); 
           v.showPresent(); 
        } 
} 
  • A. Your v: mypkg.Main@29ca2745
  • B. Your v: Your v:
  • C. It does not compile.
  • D. It compiles but throws an exception at runtime.


C.

Note

The code contains a compilation problem in regard to the contents instance variable.

The contents instance variable is marked final, but there is a setContents() instance method that can change the value of the variable.

Since these two are incompatible, the code does not compile, and Option C is correct.

If the final modifier was removed from the contents variable declaration, then the expected output would be of the form shown in Option A.




PreviousNext

Related