078.
Here, Person is the name of the class, person1 is
an object of
type Person. The new keyword is followed by the constructor for
the Person class. This allocates memory for the person1
object. The new keyword is only required to be specified with
objects and not
for primitive types like int, double, etc.
What will be the output of the following code snippet?
public class MyClass2 {
private int field1 = 0;
private static int field2 = 0;
public static void main(String[] args) {
MyClass2 object1 = new MyClass2();
object1.field1++; //Line 1
object1.field2++; //Line 2
MyClass2 object2 = new MyClass2();
object2.field1++; //Line 3
object2.field2++; //Line 4
System.out.println(object2.field1); //Line 5
System.out.println(object2.field2); //Line 6
}
}
Answer:
This code will print the following output:
1
2
Here, the class MyClass2 has 2 fields, field1 and field2.
field1 is an instance field while field2 is a static field. When
it comes to instance fields, each object of a class has its own
079.
copy of instance fields. So object1 and object2 will have their
own copies of field1 and Lines 1 and 3
will cause this copy of
the field to be incremented. However, in the case of static fields,
there is only one copy of the static fields corresponding to all the
objects of the class. So, there is only one copy of field2
corresponding to object1 and object2. So, lines 2 and 4 will
increment this same copy and cause Line 6 to print the value 2.
Do'stlaringiz bilan baham: