Reputation: 3519
package p1;
public class demo1{
public static void main(String []args){
}
protected class demo12{
protected int fun2(int a,int b){
return a*b;
}
}
package p2;
import p1.demo1;
public class demo2{
public static void main(String []args){
//access fun2 method here.
}
}
I create a package p1
and create a inner class name demo12
. And i want to access demo12
fun2
method in package p2
. How to do it?
Do any change in class demo2
. And directly or indirectly I want to access that method from class demo2
without change code of demo1
.
Upvotes: 0
Views: 4297
Reputation: 1681
In order to access your demo12
inner class from demo2
class, demo2
class has to extend demo1
. More over, inner classes are connected with instances of the class, so you can not call it directly from the static method.
Check the difference between inner and nested classes.
Static Nested Classes
As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class: it can use them only through an object reference.
Inner Classes
As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.
Edited:
I would suggest to check your design whether it class hierarchy cannot be simplified. Especially focus on difference between inner and static nested classes.
Your inner class demo12
is also marked protected, you can extend it as well. Check this hack:
package p2;
import p1.demo1;
public class demo2 extends demo1 {
protected int foo( int a, int b ) {
return (new demo22()).fun2(a, b);
}
protected class demo22 extends demo12 {
protected int fun2( int a, int b ) {
return super.fun2(a, b);
}
}
public static void main( String[] args ) {
(new demo2()).foo(2, 3);
}
}
Upvotes: 5
Reputation: 5424
Your class demo2
should inherit demo1
:
class demo2 extends demo1 {...}
Upvotes: 0