Sunday, July 12, 2009

Java question (inheritance)?

public class ColorBox


{ public ColorBox()


{ System.out.print("black ");


}


public void showColor()


{ System.out.print("red ");


}


}


public class BlueGreenBox extends ColorBox


{ public BlueGreenBox()


{ System.out.print("blue ");


}


public void showColor()


{ super.showColor();


System.out.print("green ");


}


}


The following statements occur in a client method:


ColorBox box = new BlueGreenBox();


box.showColor();





What is printed when these two lines are executed?


A. black red


B. blue green


C. blue red green


D. blue black red green


E. black blue red green








thanks, i just dont get it

Java question (inheritance)?
First of all, this statement will output%26gt;%26gt; black blue


ColorBox box = new BlueGreenBox();





since it will call the the constructor of class BlueGreenBox


the constructor of BlueGreenBox will automatically call the superclass constructor ( ColorBox) which display black,


then it return to its own constructor and display blue





The following statement will output %26gt;%26gt; red green


box.showColor();





the method showColor() at BlueGreenBox class will be executed since box is an instance of BlueGreenBox.


In the showColor() method will call the superclass method showColor which will display red.


Then it return back to its own method and display green.





So the final output is (E): black blue red green
Reply:dont think it will show red at all. cuz if it is a BlueGreenBox then it will go with the methods in BlueGreenBox first. it will prob. be black blue green
Reply:It will be E...





Constructor statement intializes parent first... so you print "Black", then you finish it with "Blue"... then you say box.showColor()... This tells parent to print its color "Red", and then finishes with printing "Green"

survey for money

No comments:

Post a Comment