Search This Blog

27 June, 2011

Nested and inner classes (contd)


• Nested classes have access to all of the
variables of the enclosing class.


• However, the enclosing class must access the
nested class variables through an object
reference.


• The key point is that the nested class can inherit
independently of the inheritance hierarchy of the
enclosing class.


• Thus, inner classes permit multiple inheritance in
practice.


• This is illustrated by the following example.


• Note: Java rejects multiple inheritance in
principle, since it permits one class to have only
one superclass.
– Inner classes do NOT negate this rule in
principle.
– However, through inner classes, one can
effectively subvert this principle in
practice.


Program:-
• In file: e:\java\kawa\pkg2\Base2.java
package pkg2;
public class Base2
{
int base2;
protected void base2Method()
{
System.out.println (“In Base 2");
}
}


• In file: e:\java\kawa\pkg1\MultipleInherit.java
package pkg1;
class Base1
{
int base1;
void base1Method()
{
System.out.println (“In Base 1");
}
}
class Derived extends Base1
{
int derivInt=2;


class Inner extends pkg2.Base2
{
void showInner()
{
base1Method();
base2Method();
//access protected method from other
//package
System.out.println (”Though I abused"+
“multiple inheritance, I still use it”);
}
}//end of class Inner
void deriv()
{
Inner i = new Inner();
i.showInner();
}}
public class MultipleInherit {
public static void main(String args[])
{
Derived d = new Derived();
d.deriv();
//Inner i = new Inner(); //illegal
//i.showInner();
} }
• Output:
In Base 1
In Base 2
Though I abused multiple inheritance, I still use it.

------------------------------
Exceptions
------------------------------

No comments:

Post a Comment

Meetme@