Page 1 of 1

About Question enthuware.ocpjp.v8.2.1590 :

Posted: Fri Feb 10, 2017 9:22 pm
by jckozy86
why does the below run with no issues, where in CODE 1 A a = new B(); calls the method from A
and with CODE B Widget w = new GoodWidget(); the method is called from GoodWidget();

Thanks,
Kozy

CODE 1:

Code: Select all

class A
{
   public void getItDone(int counter)
   {
      assert counter >= 0 : "Less than zero";
      for(int i=0; i<counter; i++){ }
   }
}
class B extends A
{
   public void getItDone(int counter)
   {
      assert counter < 100 : "Greater than 100";
      for(int i=counter; i>0; i--){ }
   }
   public static void main(String args[])
   {
      A a = new B();
      a.getItDone(-4);
   }
}
(Assume that assertions are enabled.)


CODE B:

What will the following code print when compiled and run?

Code: Select all

abstract class Widget {

    String data = "data";
    public void doWidgetStuff() {
    }

}

class GoodWidget extends Widget{
    String data = "big data";

    public void doWidgetStuff() {
        System.out.println(data);
    }
}

public class WidgetUser{
    public static void main(String[] args) {
        Widget w = new GoodWidget();
        w.doWidgetStuff();
    }
   
}

Re: About Question enthuware.ocpjp.v8.2.1590 :

Posted: Fri Feb 10, 2017 9:30 pm
by admin
Why do you think the method from A is called in the first code?

Re: About Question enthuware.ocpjp.v8.2.1590 :

Posted: Sat Feb 11, 2017 5:47 pm
by jckozy86
I'm sorry,

it was late and was reading the explanation in a sleepy state.

Re-read the explanations and in both cases, since the passed object has the method, that one gets used.

Thanks!

Re: About Question enthuware.ocpjp.v8.2.1590 :

Posted: Mon Dec 24, 2018 1:41 am
by d0wnvk@gmail.com
Hi there))

The whole purpose of assertions: that the program should fail if that assumption fails.
With counter value as -4 the assertion returns true and no program fail occurs (and the program continues to proceed).
Why is the loop is never entered ?
What I'm missing out ?

Re: About Question enthuware.ocpjp.v8.2.1590 :

Posted: Mon Dec 24, 2018 3:54 am
by admin
Inside the getItDone method, counter is -4, so, the assertion counter>100 is satisfied. Therefore, no AssertionError will be thrown here. Further, since counter is -4, for condition counter>0 is not satisfied and so the loop will not be entered.

Re: About Question enthuware.ocpjp.v8.2.1590 :

Posted: Mon Dec 24, 2018 5:09 am
by d0wnvk@gmail.com
Thanks for reply and pointing me out.
Foreach condition - shame on me((

Re: About Question enthuware.ocpjp.v8.2.1590 :

Posted: Mon Mar 29, 2021 6:38 am
by Oussama
The problem here is with the for loop :
for(int i=counter; i>0; i--){ }
i = -4 ; so i >0 will return false --------> The loop is never entered and the program terminates.