What is the difference between these two ways of instantiating new objects of a class as follows:
Test t1=new Test(); Test t2=new Test(){ };
When I tried the following code, I could see that both objects could access the method foo()
, but t2 cannot access the variable x
(variable x
cannot be resolved):
public class Test { int x=0; public void foo(){ } public static void main (String args[]) { Test t1=new Test(); Test t2=new Test(){ }; t1.x=10; t2.x=20; t1.foo(); t2.foo(); System.out.println(t1.x+" "t2.x); } }
What differences are there between the different levels of testing? The focus shifts from early component testing to late acceptance testing. It is important that everybody understands this. There are generally four recognized levels of testing: unit/component testing, integration testing, system testing, and acceptance testing.
The next level of testing is system testing. As the name implies, all the components of the software are tested as a whole in order to ensure that the overall product meets the requirements specified.
Unit testing is usually done by the developers side, whereas testers are partly evolved in this type of testing where testing is done unit by unit. In Java JUnit test cases can also be possible to test whether the written code is perfectly designed or not.
Test t2=new Test (); will create the object of Test class. But Test t2=new Test () { }; will create a object of subclass of test (i.e. anonymous inner class in this case). you can provide implementation for any method over there like Test t2=new Test () { public void foo () { System.out.println ("This is foo");} };
Test t2=new Test();
will create the object of Test class.
But Test t2=new Test(){ };
will create a object of subclass of test (i.e. anonymous inner class in this case).
you can provide implementation for any method over there like
Test t2=new Test(){ public void foo(){ System.out.println("This is foo");} };
so that when foo()
method called from object t2
it will print This is foo
.
Addition
Compile time error in your code is due to missing concatination operator
System.out.println(t1.x+" "+t2.x); ###
The runtime type of both the references would be different. Try:
System.out.println(t1.getClass()); // class Test System.out.println(t2.getClass()); // class Test$1
You will see different output. Reason being, the new Test() { }
expression creates instance of an anonymous subclass of Test
. So, Test$1
is a subclass of Test
.
Now, the reason you're getting that error is, you're missing a +
sign:
System.out.println(t1.x + " " + t2.x); ^
You can find more details on this post, and this post
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With