Protected Inner Classes
Having difficulty debugging the following:
pkg1; public interface I1 { void method1(); }
pkg2: import pgk1.*;
public class C2
protected int i2 = 2;
protected class C2Inner1 implements I1
public void method1()
{ System.out.println("This is C2Inner1.method1."); }
pkg3: import pgk1.*;
import pgk2.*;
class C3 extends C2
I1 createC2Inner1()
C3 z = new C3();
return z.new C2Inner1(); // Line 1
// return new C2Inner1(); // Line 2
// return new C3.C2Inner1(); // Line 3
// return new z.C2Inner1(); // Line 4
public static void main(String[] args)
C3 a = new C3();
a.i2 = 3; // Line 5
I1 x = a.createC2Inner1();
x.method1();
Line 5 runs okay, which indicates that my understanding of protected is ok.
Lines 1 through 4 all cause the same compile error:
C2Inner1() has protected access in pkg2.C2.C2Inner1
When I change C2Inner1 access to public, Lines 1 through 4 each work okay.
Why can I access i2 but not C2Inner1 (i.e. when both protected)? Is there
different syntax to handle this specific situation?
/*
this.new Inner() ?
Similar Messages
-
Can I create the object of an protected inner class of a Base class in to t
Dear All,
Can I create the object of an protected inner class of a Base class in to the subclass ?
e.g.
public class Base{
protected class Inner {};
Public class Sub extends Base{
Public Inner amethod (){
Return new Inner(); //here I get an exception as
//Inner has protected access
}Regards,
Ishan@Op. The code that you posted isn't close to compiling. Java is case sensitive. It should be public and not Public, and return instead of Return.
Kaj -
Hi All,
Sorry for my English...
Say I have an abstract Class A and and inner class within A named B.
When I extend class A (i.e. making a subclass of A) does it mean the class B also inheritaned?
Thank u in advance
EyalEyal2007 wrote:
Does inner class of an outer abstract class can be static?Yes, why not?
is there any logic in this?Yes, if follows the normal meanings of access types and the difference between static and instance entities.
A protected inner class is accessible in the same places a protected field would be. -
Why are protected fields not-accessible from sub-classed inner class?
I ran across a situation at work where we have to sub-class an inner class from a third-party package. So, it looks something like this...
package SomePackage;
public class Outer {
protected int x;
public class Inner {
package OtherPackage;
public class NewOuter extends Outer {
public class NewInner extends Outer.Inner {
}Now the NewInner class needs to access protected variables in the Outer class, just like the Inner class does. But because NewOut/NewInner are in a different package I get the following error message.
Variable x in class SomePackage.Outer not accessible from inner class NewOuter. NewInner.You can still access those protected variables from the NewOuter class though. So, I can write accessor methods in NewOuter for NewInner to use, but I am wondering why this is. I know that if NewOuter/NewInner are in the same package as Outer/Inner then everything works fine, but does not when they are in different packages.
I have to use JDK1.1.8 for the project so I don't know if there would be a difference in JDK1.2+, but I would think that nothing has changed. Anyway, if you know why Java disallows access as I have detailed please let me know.Although I don't have the 1.1.8 JDK installed on my system, I was able to compile the following code with the 1.3.1_01 JDK and run it within a Java 1.1.4 environment (the JVM in the MSIE 5.5 browser). As long as you don't access any of the APIs that were introduced with 1.2+ or later, the classes generated by the JDK 1.2+ javac are compatible with the 1.1.4+ JVM.
//// D:\testing\SomePackage\Outer.java ////package SomePackage ;
public class Outer {
protected int x ;
public Outer(int xx) {
x = xx ;
public class Inner {
}//// D:\testing\OtherPackage\NewOuter.java ////package OtherPackage;
import SomePackage.* ;
public class NewOuter extends Outer {
public NewOuter(int xx) {
super(xx) ;
public class NewInner extends Outer.Inner {
public int getIt() {
return x ;
}//// D:\testings\Test.java ////import OtherPackage.* ;
import java.awt.* ;
import java.applet.* ;
public class Test extends Applet {
public void init () {
initComponents ();
private void initComponents() {
add(new Label("x = ")) ;
int myx = new NewOuter(3288).new NewInner().getIt() ;
TextField xfld = new TextField() ;
xfld.setEditable(false) ;
xfld.setText(Integer.toString(myx)) ;
add(xfld) ;
}//// d:\testing\build.cmd ////set classpath=.;D:\testing
cd \testing\SomePackage
javac Outer.java
cd ..\OtherPackage
javac NewOuter.java
cd ..
javac Test.java//// d:\testing\Test.html ////<HTML><HEAD></HEAD><BODY>
<APPLET CODE="Test.class" CODEBASE="." WIDTH=200 HEIGHT=100></APPLET>
</BODY></HTML> -
Problem with final variables and inner classes (JDK1.1.8)
When using JDK1.1.8, I came up with following:
public class Outer
protected final int i;
protected Inner inner = null;
public Outer(int value)
i = value;
inner = new Inner();
inner.foo();
protected class Inner
public void foo()
System.out.println(i);
}causing this:
Outer.java:6: Blank final variable 'i' may not have been initialized. It must be assigned a value in an initializer, or in every constructor.
public Outer(int value)
^
1 error
With JDK 1.3 this works just fine, as it does with 1.1.8 if
1) I don't use inner class, or
2) I assign the value in initializer, or
3) I leave the keyword final away.
and none of these is actually an option for me, neither using a newer JDK, if only there is another way to solve this.
Reasons why I am trying to do this:
1) I can't use a newer JDK
2) I want to be able to assign the variables value in constructor
3) I want to prevent anyone (including myself ;)) from changing the value in other parts of the class (yes, the code above is just to give you the idea, not the whole code)
4) I must be able to use inner classes
So, does anyone have a suggestion how to solve this problem of mine? Or can someone say that this is a JDK 1.1.8 feature, and that I just have to live with it? In that case, sticking to solution 3 is probably the best alternative here, at least for me (and hope that no-one will change the variables value). Or is it crappy planning..?You cannot use a final field if you do not
initialize it at the time of declaration. So yes,
your design is invalid.Sorry if I am being a bit too stubborn or something. :) I am just honestly a bit puzzled, since... If I cannot use a final field in an aforementioned situation, why does following work? (JDK 1.3.1 on Linux)
public class Outer {
protected final String str;
public Outer(String paramStr) {
str = paramStr;
Inner in = new Inner();
in.foo();
public void foo() {
System.out.println("Outer.foo(): " + str);
public static void main( String args[] ) {
String param = new String("This is test.");
Outer outer = new Outer(param);
outer.foo();
protected class Inner {
public void foo() {
System.out.println("Inner.foo(): " + str);
} producing the following:
[1:39] % javac Outer.java
[1:39] % java Outer
Inner.foo(): This is test.
Outer.foo(): This is test.
Is this then an "undocumented feature", working even though it shouldn't work?
However, I assume you could
get by with eliminating the final field and simply
passing the value directly to the Inner class's
constructor. if not, you'll have to rethink larger
aspects of your design.I guess this is the way it must be done.
Jussi -
Problem with constructor of inner class.
Hi everybody!
I have an applet which loads images from a database.
i want to draw the images in a textarea, so i wrote an inner class, which extends textarea and overrides the paint method.
but everytime i try to disply the applet in the browser this happens:
java.lang.NoClassDefFoundError: WohnungSuchenApplet$Malfl�che
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:1590)
at java.lang.Class.getConstructor0(Class.java:1762)
at java.lang.Class.newInstance0(Class.java:276)
at java.lang.Class.newInstance(Class.java:259)
at sun.applet.AppletPanel.createApplet(AppletPanel.java:567)
at sun.plugin.AppletViewer.createApplet(AppletViewer.java:1778)
at sun.applet.AppletPanel.runLoader(AppletPanel.java:496)
at sun.applet.AppletPanel.run(AppletPanel.java:293)
at java.lang.Thread.run(Thread.java:536)
so my class has no own constructor, it just has the paint method overwritten.
my class looks like this:
public class Malfl�che extends javax.swing.JTextArea{
public void paint(Graphics g){
Color grey=new Color(220,220,220);
g.drawImage(img,10,10,null);
how should a constructor for this class look like?
sorry i am quite new to this, so i really dont have a clue!
my class does not have any attributes or requires any so it doesnt need a constructor, doesnt it?
thanks a lot
timFirst off, unlike regular classes, inner classes can be declared public, private, protected, and default.
Secondly, why are you using the JTextArea to display an image, why not use a JLabel, which takes an Image object as its constructor.
Thirdly, when you drew your image you did not give it a width and height
g.drawImage(img, 0,0, img.getWidth(null), img.getHeight(null), null);
otherwise it will make your image 1 X 1 pixels. not big enough to see. -
Compiler error when useing switch statements in an inner class
I have defined several constants in a class and want to use this constans also in an inner class.
All the constants are defined as private static final int.
All works fine except when useing the switch statement in the inner class. I get the compiler error ""constant expression required". If I change the definition from private static final to protected static final it works, but why?
What's the difference?
Look at an example:
public class Switchtest
private static final int AA = 0;
protected static final int BB = 1;
private static int i = 0;
public Switchtest()
i = 0; // <- OK
switch(i)
case AA: break; //<- OK, funny no problem
case BB: break; //<- OK
default: break;
private class InnerClass
public InnerClass()
i = 0; // <- OK: is accessible
if (AA == i) // <- OK: AA is seen by the inner class; i is also accessible
i = AA + 1;
switch(i)
case AA: break; // <- STRANGE?! Fail: Constant expression required
case BB: break; // <- OK
default: break;
}Thank's a lot for an explanation.Just a though:
Maybe some subclass of Switchtest could decalare its own variable AA that is not final, but it can not declare its own BB because it is visible from the superclass. Therefore the compiler can not know for sure that AA is final. -
Getting the name of outer class in an inner class
Hi,
I have a private inner class, something like this:
public class OuterClass extends AnotherClass {
public OuterClass() {
supre();
private class innerClass1 extends SomeotherClass {
protected void someMethod() {
// how to get the name of outer class, that is, "OuterClass"
Can someone please tell me how to get the name of the outer class inside the inner class method?
Thanks in advance..
PrasannagetClass().getEnclosingClass().getName()But then, you already know it, don't you?
-
How to override a method in an inner class of the super class
I have a rather horribly written class, which I need to adapt. I could simply do this if I could override a method in one of it's inner classes. My plan then was to extend the original class, and override the method in question. But here I am struggling.
The code below is representative of my situation.
public class ClassA
ValueChecks vc = null;
/** Creates a new instance of Main */
public ClassA()
System.out.println("ClassA Constructor");
vc = new ValueChecks();
vc.checkMaximum();
// I want this to call the overridden method, but it does not, it seems to call
// the method in this class. probably because vc belongs to this class
this.vc.checkMinimum();
this.myMethod();
protected void myMethod()
System.out.println("myMethod(SUPER)");
protected class ValueChecks
protected boolean checkMinimum()
System.out.println("ValueChecks.checkMinimum (SUPER)");
return true;
protected boolean checkMaximum()
return false;
}I have extended ClassA, call it ClassASub, and it is this Class which I instantiate. The constructor in ClassASub obviously calls the constructor in ClassA. I want to override the checkMinimum() method in ValueChecks, but the above code always calls the method in ClassA. The ClassASub code looks like this
public class ClassASub extends ClassA
public ClassAInner cias;
/** Creates a new instance of Main */
public ClassASub()
System.out.println("ClassASub Constructor");
protected void myMethod()
System.out.println("myMethod(SUB)");
protected class ValueChecks extends ClassA.ValueChecks
protected boolean checkMinimum()
System.out.println("ValueChecks.checkMinimum (SUB)");
return true;
}The method myMethod seems to be suitably overridden, but I cannot override the checkMinimum() method.
I think this is a stupid problem to do with how the ValueChecks class is instantiated. I think I need to create an instance of ValueChecks in ClassASub, and pass a reference to it into ClassA. But this will upset the way ClassA works. Could somebody enlighten me please.vc = new ValueChecks();vc is a ValueChecks object. No matter whether you subclass ValueChecks or not, vc is always of this type, per this line of code.
// I want this to call the overridden method, but it does not, it seems to > call
// the method in this class. probably because vc belongs to this class
this.vc.checkMinimum();No, it's because again vc references a ValueChecks object, because it was created as such.
And when I say ValueChecks, I mean the original class, not the one you tried to create by the same name, attempting to override the original. -
Inner class vs. imported class
Hi everyone,
I have entitiy beans created for a client's web app I'd like to use in the
web service using WebLogic Workshop 7.0. Say the classes are imported like
this in the services:
import com.hoike.clientname.ap.bean.Invoice
import com.hoike.clientname.ap.bean.Vendor
Instances of these classes are used in callback methods and some of the
service methods.
When I generate the CTRL file, it actually adds those imported classes as
inner class of the service defined.
The problem is that when I try to used these services from another service,
I cannot use the imported classes (as Invoice or Vendor), but instead I have
to use the inner class (InvoiceService.Invoice or VendorService.Vendor)
Does WebLogic Workshop 7.0 only allow you to use inner classes? Is there a
way to use custom classes as method parameters?
Thanks in advance!
Makotohow do you declare your inner class?
Is it (public)
public static class MyInnerClassor (private)
private static class MyInnerClassor (package)
static class MyInnerClassor (protected)
protected static class MyInnerClassTry to change the way you declare the inner class. Use protected or package or public instead. -
Are enums and inner classes allowed in taglib function signatures??
Hi,
I have a taglib with the following function definition:
<function>
<description>Determine if viewing a patient attribute is allowed</description>
<name>isViewingPatientAttributeAllowed</name>
<function-class>com.example.admin.authorization.UserAuthorizer</function-class>
<function-signature>boolean isViewingPatientAttributeAllowed(com.example.bean.User, com.example.bean.Patient.PatientAttribute, com.example.bean.Patient)</function-signature>
<example>
${ncvi:isViewingPatientAttributeAllowed(user, patientAttribute, patient)}
</example>
</function>Where com.example.bean.Patient.PatientAttribute is an enum (note package names have been changed to protect the innocent;-). When I try to compile my web app I get the following error:
org.apache.jasper.JasperException: The class com.example.bean.Patient.PatientAttribute specified in the method signature in TLD for the function ncvi:isViewingPatientAttributeAllowed cannot be found. com.example.bean.Patient.PatientAttributeIf I change PatientAttribute to a static inner class of Patient, I still get the error. Are enums and inner classes allowed in function signatures?
Thx.I think that you'll find it easier to define a non-inner abstract class RefBase, that exposes a removeFromQueue() method, then extend that for your Ref class. That way, the queue just deals with RefBase instances (or ? extends RefBase).
I think that any other approach is going to get the compiler confused, because the compile-time Ref depends on the parameterization of its defining class. -
Reference to enclosing instance in inner class constructor
Is there any Java compiler which assigns reference to enclosing instance in constructor of inner clase before invoking super class constructor?
class Outer {
class Inner extends Global {
public Inner(int x) {
// I want (Outer.this != null) here
super();
class Global {
public Global(int x) {class Outer {
class Inner extends Global {
public Inner(int x) {
// I want (Outer.this != null) hereOuter.this is never null at this point. A non-static
inner class always has an implicit reference to an
instance of the enclosing class.Try this:
class Outer {
int m;
class Inner extends Global {
public Inner(int x) {
super(x);
protected void init(int x) {
xxx = Outer.this.m + x; // Null pointer exception!!!
class Global {
int xxx;
public Global(int x) {
init(x);
protected void init(int x) {
xxx = x; -
Generics and inner classes?
How can I say my inner class uses the same type as it's genericised host class?
Should I just not declare a "generic" type in the inner class?
The code
public class LinkedList<E> implements java.util.List<E>
... code omitted for brevity ...
* An internal implementation of java.util.Iterator.
private class Iterator<E> implements java.util.Iterator<E> {
protected Node<E> current;
public Iterator() {
this.current = head; // error here
... code omitted for brevity ...
produces the compiler error
C:\Java\home\src\linkedlist\LinkedList.java:59: incompatible types
found : linkedlist.LinkedList.Node<E>
required: linkedlist.LinkedList.Node<E>
this.current = head;
^I understand the meaning of the compiler error... it's effectively saying that "E" is not the same type within in the Iterator class as it is in the parent LinkedList class... What I don't understand is how to make E the same type within the Iterator... if I just leave the <E> off of Iterator<E> then it throws "unchecked operation" warnings... do I just have to put up with these warnings... but no that can't be right because java.util.LinkedList has an iterator and it's not throwing unchecked operation compiler warnings... so there has to be a way...
Thanx all. Keith.One more dumbshit question...
Is there a way to do this without the warnings OR the @SuppressWarnings({"unchecked"})
* Returns the index of the last occurrence of the specified element in this
* list, or -1 if this list does not contain the element.
//@SuppressWarnings({"unchecked"})
public int lastIndexOf(Object object) {
int i = 0;
int last = -1;
for(Node<E> node=this.head.next; node!=null; node=node.next) {
if (node.item.equals((E) object)) {
last = i;
i++;
return(last);
produces the warning
C:\Java\home\src\linkedlist\LinkedList.java:313: warning: [unchecked] unchecked cast
found : java.lang.Object
required: E
if (node.item.equals((E) object)) {
^... remembering that List specifies +public int lastIndexOf(Object object);+ as taking a raw Object, not E element, as I would have expected.
Thanx all. Keith. -
Re: Inheritance and Inner classes
Sorry all,
I forgot to include that I loose the inner classes in codesense. And
the editor will not let me reference them.
Thanks again,
Stu
"Stu Pidasso" <[email protected]> wrote in message
news:41fe9aac$[email protected]..
Hello all,I'm an Eclipse and Nitro newby here, and I was wondering if anyone had any
insight into this. I'm subclassing a "Constants" class that contains some
static variables, static methods and static inner classes. Once I
subclass,
and refer to my new class, I loose all the parent class' inner classes.
Is
there a way around this? Or, am I hosed and have to put in a bug report
somewhere? I know that in JBuilder this functionality works fine.
Thanks,
StuK ive done as suggested and added a constructor that calls its superclass contrustor but its still not working. :(
Any clues ?
public abstract class shape {
int pi;
int radius;
class twoD extends shape {
twoD(int r, int p) { //constructor for circle
radius = r;
pi = p;
public void setAreaCircle() { // area of circle method
int circleArea = pi * radius^radius;
System.out.println(circleArea);
public void setCircumCircle() { // circumfreanceof circle method
int circleCircum = 2 * pi^radius;
System.out.println(circleCircum);
public class circle extends twoD {
public static void main(String args[]) {
public circle(int r, int p) { // call to superclass constructor
super(r,p);
twoD ob = new twoD(5,10);
ob.setAreaCircle();
ob.setCircumCircle(); -
Calling an inner class in a jsp:usebean tag
Hi everybody !
Here's my problem : working in my project on multiple pages, I'm using inner classes/beans to limitate my '.java' files but I'm stuck when calling that 'inner-bean' in my jsp:usebean tag.
First, I tried to declare in the class parameter : 'class="MyPrincipalBean.theInnerBean" but jsp returns me a 'not found' message.
I tried an other issue with this :
'class="MyPrincipalBean$theInnerBean" but I encountered a 'Attempt to use a bean type without a void constructor in jsp:useBean tag (JSP 1.1 specification, 2.13.1)'. Since I can't find that specification, I'm sending an SOS.
Am I on the good way ? If somebody as encoutered that sort of problem, it would be very kind of you to help me.
Thanks for your help !
[email protected]Thanks for your help!
I must recognize that my explainations weren't really precise.
My principal bean owns a table of my inner-class type :
public class FirstBean extends EntityBean {
private SecondBean[] tabSB;
public SecondBean[] getTabSB() {...}
public void setTabSB(SecondBean[] p_tabSB) {...}
public class SecondBean {...}
So I can call a specific bean from the tab in my Servlet for another page.
But I think I have the solution and I need your advise :
I tried this :
<jsp:useBean id="FirstBean" class="<...>.FirstBean" scope="session" />
<jsp:useBean id="SecBean" beanName="<...>.FirstBean$SecondBean" type="<...>.FirstBean$SecondBean" scope="request" />
And would you believe it ? It seems to work ! But I have to test this farther to be sure. What do you think of it ?
Maybe you are looking for
-
Volume botton problem in lumia 520
I had noticed many times that my lumia's volume was not working even though I minimized volume.
-
Itunes will not install after removing itself.
a few months ago i turned my laptop on to find that itunes had uninstalled itself. so i went on to the software update which is downloaded onto my computer i tried to install itunes back, but it would get so far then not install. i have tried several
-
Query Works in Query Designer - Doesn't Work in Report
I have a report that runs just fine in the Query Designer, but for some reason does not run when I run the actual report. Here is the query in question: SELECT {[Measures].[Employee Hours]} ON COLUMNS ,NON EMPTY [Employee].[Employee Full Name].[Emplo
-
I renamed my Apple ID with new name but the old password is no more working. What should I do ? After renaming I am getting pop up message regarding icloud on my screen but I am unable to set off the message box now
-
How do I import photos from iPhoto to Lightroom on mac book air?
Iv'e read in several forums that to do this you must go into the finder right click on iPhoto. Click show package contents. This pulls up a file named contents. All of the forums say to either look for a masters file or a original file and copy