• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inner Classes inheritance

 
Joe Harry
Ranch Hand
Posts: 10112
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

Can a non static inner class be a sublass of its outerclass?

Consider the following code as,

class Outer{
private int a = 10;
class Inner extends Outer{
...........
...........
...........
}
}

Will the above be logical? Please anyone give me explanation in terms of real time programming.

Regards,
Jothi Shankar Kumar. S
 
Ali Gohar
Ranch Hand
Posts: 572
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes i think its legal
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What happens when you write some java code, compile, and run it?
That's the way to find the answer to such questions if you do not want to read the Java Language Specification.
 
Joe Harry
Ranch Hand
Posts: 10112
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Barry,

Here is the code that I had doubt,

class outer {
private int a = 10;
class inner {
public void myMethod(){
System.out.println(this.a); //throws error here but works good when using the special this operator like outer.this.a
}
}
}

Why the above throws error at the line mentioned but when said
class inner extends outer this.a works fine. Reason?

Regards,
Jothi Shankar Kumar. S
 
wise owen
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The name this.x refers to a variable named x in this instance of the object. It is pretty obvious that if you refer to this in an inner class, it refers to fields or variables defined in the inner class itself.
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why the above throws error at the line mentioned but when said
class inner extends outer this.a works fine. Reason?


Simply because it cannot inherit x from its superclass because it is private. If you make x accessible using this.x (or just x) in the println will work.

Compile and run this code:


Can you now see what is happening?

Make x private again and compile. Then comment out the line that does not compile and compile and run it again. Can you see the difference?
[ October 06, 2006: Message edited by: Barry Gaunt ]
 
Joe Harry
Ranch Hand
Posts: 10112
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Barry,

Thanks for the reply and you gave a reasonable explanation. Thanks for it. I understood.

Regards,
Jothi Shankar Kumar. S
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic