神刀安全网

Java Quiz: Passing Objects to Constructors

Last Week’s Quiz

Here’s the answer to last week’s quiz:

  • Line 03- "x" is a static variable which belongs to the class not to the objects.

  • Line 04- sb2 is a static object and it belongs also to the class.

  • Line 07- each time you instantiate “MyClass” method and method2 are executed and each one of them add “3” to the value of “x”.

  • Line 13- The object "sb" is not static. Each time you instantiate "MyClass", "sb" belongs only to that object. However, it appends the value "x" which belongs to the class "MyClass"

  • We have created 3 objects.

  • By creating an object, method and method2 both are executed and each one of them add 3 to the value of “x” which is 0.

The First Part: mc2.sb

By creating the first object "mc", “method” and “method2” are executed. Each one of them adds 3 to the value of x.

x = 0 + 3 + 3 = 6.

By creating the second object mc2, method is executed, which adds "3" to the last value of x.We print the value of x to the standard output before method2 is executed. That is why 

x = 6 + 3 = 9.

Remember that x is a static variable, but "sb" is not static.

The Second Part

By creating the first object mc: x = 0 + 3 + 3 = 6

By creating the second object mc2 x = 6 + 3 + 3 = 12

By creating the third object mc3 x = 12 + 3 + 3 = 18

The method append(int i). Appends the string representation of the int argument. See “StringBuffer” Java API!

That is why mc2.sb2 prints " 61218 " to the standard output and that applies to all the objects, because sb2 is static.

The final result is: "9-61218"

This Week’s Quiz

Purpose

  1. To introduce behaviors of passing objects to constructors.

  2. To help you imagine complex procedures in Java.

  3. This quiz is aimed at advanced Java Programmers.

What is written to the standard output as a result of executing the following code?

public class ClassB {      int x = 3;      public ClassB() {         System.out.print(new ClassA().method());     }     public ClassB(int i) {         System.out.print(i);     }     public int method(int i){         return x + i;     } }  public class ClassA {      int y;      public ClassA() {}      public ClassA(ClassB classB) {         System.out.print(classB.method(1));     }     public int method(){         System.out.print(new ClassB(4).method(3));         return y;     }     public static void main(String[] args){         ClassA classA = new ClassA(new ClassB(new ClassB().method(2)));     } }

Let us know if you have any questions or comments, and check out Sar’s site here.

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Java Quiz: Passing Objects to Constructors

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址