From OCP Oracle Certified Professional Java SE 11 Programmer I Exam Fundamentals 1Z0-815: Study guide for passing the OCP Java 11 Developer Certification Part 1 Exam 1Z0-815 (English Edition) pages 235 and 237:
...
ic.printCount();
new InstanceCounter(). printCount();
System.out.println( InstanceCounter.printCount() +" "+ InstanceCounter.count);
...
will print:
1
2
2 2
I understand that first and second line the constructor is executed but in the last line it is not executed, right?
What will 10.5.3 example print
Moderator: admin
-
- Posts: 16
- Joined: Mon Sep 30, 2019 11:40 am
- Contact:
-
- Site Admin
- Posts: 10404
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: What will 10.5.3 example print
Correct. new InstanceCounter() creates an instance of InstanceCounter class.
Code: Select all
public static void main(String[] args){
InstanceCounter ic = new InstanceCounter(); // creates an instance, so the constructor is executed, which increments count to 1
ic.printCount(); //print 1 because count is 1
new InstanceCounter().printCount(); //creates an instance, so the constructor is executed , which increments count to 2. printCount prints 2
System.out.println(InstanceCounter.printCount()+" "+InstanceCounter.count); //no instance is created, so, count is not affected, therefore printCount prints 2 and 2
}
Who is online
Users browsing this forum: Bing [Bot] and 18 guests