Page 1 of 1

enthuware.ocajp.i.v7.2.1131

Posted: Wed Mar 14, 2018 10:20 am
by ashishrai.kv

Code: Select all

What would be the result of attempting to compile and run the following program?

class TestClass{
   static TestClass ref;
   String[] arguments;
   public static void main(String args[]){
      ref = new TestClass();
      ref.func(args);
   }
   public void func(String[] args){
      ref.arguments = args;
   }
}

one of the incorrect answer explained is :-The concept here is that a non-static method (i.e. an instance method) can only be called on an instance of that class. Whether the caller itself is a static method or not, is immaterial. The main method is calling ref.func(); - this means the main method is calling a non-static method on an actual instance of the class TestClass (referred to by 'ref'). Hence, it is valid. It is not trying calling it directly such as func() or this.func(), in which case, it would have been invalid.


and correct answer for above problem is that it will compile as here ref is static and invoking func(String args) will not be any problem.

can you show examples or scenarios by modifying the above example only as when it will show an error while accessing the main method?

Re: enthuware.ocajp.i.v7.2.1131

Posted: Wed Mar 14, 2018 11:30 am
by admin
As the explanation says, you can change ref.func() to func() or this.func() to fail compilation.

Re: enthuware.ocajp.i.v7.2.1131

Posted: Mon Jun 25, 2018 5:04 am
by eyal1983
I do not understand;

How can a static variable ("ref" - in this example) call a non-static method ("func")?

Re: enthuware.ocajp.i.v7.2.1131

Posted: Mon Jun 25, 2018 5:28 am
by admin
eyal1983 wrote:
Mon Jun 25, 2018 5:04 am
I do not understand;

How can a static variable ("ref" - in this example) call a non-static method ("func")?
You have asked a very basic question. You should go through a good book to understand the concept of static and instance before trying to make sense of this. But in short, whether ref is static or non-static is irrelevant. What is important is that ref is a reference variable that points to an object of TestClass. The method func is being invoked on this object.

Again, my suggestion is that you should not be attempting mock exams at this stage of your preparation because your fundamentals are too weak.

Re: enthuware.ocajp.i.v7.2.1131

Posted: Tue Jun 26, 2018 10:51 am
by eyal1983
whether ref is static or non-static is irrelevant. What is important is that ref is a reference variable that points to an object of TestClass. The method func is being invoked on this object.
-Thanks!

Which book do you prefer?

Re: enthuware.ocajp.i.v7.2.1131

Posted: Wed Jun 27, 2018 6:48 am
by admin
You can go with either one of the two mentioned here: http://enthuware.com/index.php/mock-exa ... fication-8

Re: enthuware.ocajp.i.v7.2.1131

Posted: Wed Jun 27, 2018 6:53 am
by eyal1983
OK 10x