• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

inner classes question.

 
Minhaj Mehmood
Ranch Hand
Posts: 400
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given the declaration

which of the following methods are valid?


Select the two correct answers.
(a)The method labeled (1).
(b)The method labeled (2).
(c)The method labeled (3).
(d)The method labeled (4).
(e)The method labeled (5).
---

correct answers are (d) and (e).
why (a), (b) and (c) are not correct



Ref: K.Mughal page#383
 
Raju Champaklal
Ranch Hand
Posts: 521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
a and b are incorrect as you cant make an instance of an Interface and 3rd is wrong because in that the inner class cant access the variable i of the method....

let me see the 4th and 5th options now
 
Raju Champaklal
Ranch Hand
Posts: 521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yup and in the 4th... the variable i is final so the inner class can access it....so its right
 
Minhaj Mehmood
Ranch Hand
Posts: 400
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
correct
 
Neha Daga
Ranch Hand
Posts: 504
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Raju Champaklal wrote:a and b are incorrect as you cant make an instance of an Interface and 3rd is wrong because in that the inner class cant access the variable i of the method....

let me see the 4th and 5th options now


1st & 2nd are wrong not because you cant create instance of interfaces, Raju please read K&B inner classes chapter. while making anonymous inner classwhich implements an interface the syntax is :
SomeInterface s = new SomeInterface(){};

1st is wrong because it is accesseing a non final variable 'i' in the method.
2nd is wrong because it misses () in the declaration(return new IntHolder {....) it should have been: return new IntHolder(){...

 
Raju Champaklal
Ranch Hand
Posts: 521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
oh ya....Neha is right.....
 
Minhaj Mehmood
Ranch Hand
Posts: 400
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
actually i didn't read properly raju;s reply i just matched the ans keys!
but Neha's explanation is 100% right!

Answer explanation in book:
--
The methods labeled (1) and (3) will not compile, since the non-final parameter i
is not accessible from within the inner class. The syntax of the anonymous class in
the method labeled (2) is not correct, as the parameter list is missing.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic