• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

two inner classes with the same name

 
Ilakya Mukunth
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

The output:
I am in the arg constructor
why the line-1 is not executed. why it does not create a new object of B

if i uncomment the line //A aa = new A();
output is:
I am in the arg constructor
I am in no-arg constructor

Can anyone explain the reason why?
 
Pratyush Verma
Greenhorn
Posts: 2
C++ Chrome Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am in the arg constructor
why the line-1 is not executed. why it does not create a new object of B

Line 1 wont be executed in first case because in A a = new A(1); call to A(int i) constructor is made and the instance of inner class B inside A(int i) is created.

if i uncomment the line //A aa = new A();
output is:
I am in the arg constructor
I am in no-arg constructor


That's because call to A() constructor is made and in this case line 1 is also executed to create an instance of your inner class inside A() constructor.
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to CodeRanch Pratyush Verma
 
Ilakya Mukunth
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pratyush Verma wrote:
I am in the arg constructor
why the line-1 is not executed. why it does not create a new object of B

Line 1 wont be executed in first case because in A a = new A(1); call to A(int i) constructor is made and the instance of inner class B inside A(int i) is created.
if i try to create instance of class B in constructor A() (shown below), still it does not print the "I am in no-arg constructor"
A()
{
class B
{
{ System.out.println("I am in no-arg constructor"); }
}
new B();
}
if i uncomment the line //A aa = new A();
output is:
I am in the arg constructor
I am in no-arg constructor


That's because call to A() constructor is made and in this case line 1 is also executed to create an instance of your inner class inside A() constructor.
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ilakya, just for clarity , you cant have two inner classes with same name, because of name collision in the same scope.
but you can have two different *method local inner classes* with same name in different block since both live in their own scope.
 
Pratyush Verma
Greenhorn
Posts: 2
C++ Chrome Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Seetharaman Venkatasamy wrote:Welcome to CodeRanch Pratyush Verma

Thank you Seetharaman Venkatasamy.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic