Query: Accessing super class
hi friends ,
i have a small doubt on accessing super class using super keyword.
does the use of super as super(super(super(i))); work properly
and what would be the result.
kindly guide me..........
jay
What do you expect that to do? Is that supposed to be a call to a super constructor? (and then super-super, and then super-super-super).
In any case, you can only call things from the immediate superclass (the parent). If you think you need to call the superclass' superclass (the grandparent), you likely have a bad design.
What are you trying to do?
Similar Messages
-
Accessing super class private variables from derived class
posted November 01, 2005 08:20 PM Profile for kenji mapes Email kenji mapes Send New Private Message Edit/Delete Post Reply With Quote Assume I have a default and a param constructor in both a subclass and a super class. The members are private.
So after validation logic in the sub class param. constructor, I want to access an instance variable of the super class's default constructor to set the subclass's matching variable to the default in the super class.
Is there anyway I can do this. Of course, I have inherited setters and getters.
Thanks.posted November 01, 2005 08:20 PM Profile for
kenji mapes Email kenji mapes Send New Private
Message Edit/Delete Post Reply With QuoteI suppose this is the result of an attempted crossposting from another forum. :) -
Accessing Super Class of Super Class
Consider the following classes
Class A {
print() {
System.out.println("Class A Called");
Class B extends A {
print() {
System.out.println("Class B Called");
Class C extends B {
print() {
System.out.println("Class C Called");
How can I call the print method of class A while working in class C ? Please state all possible solutions.
Can it somehow be done using super ?RZP wrote:
Consider the following classes
Class A {
print() {
System.out.println("Class A Called");
Class B extends A {
print() {
System.out.println("Class B Called");
Class C extends B {
print() {
System.out.println("Class C Called");
How can I call the print method of class A while working in class C ? Please state all possible solutions.
Can it somehow be done using super ?Here is one possible solution.
I really don't understand the ramifications of reflection... and am not familiar with OOP design... but reflection seems to enable a programmer to avoid OOP design principals as well as type-checking. While I like reflection, most of my readings suggest to rarely use it.
public class Main {
public static void main(String[] args) {
try {
new C(789).print();
} catch(Exception e) { e.printStackTrace(); }
static class A {
protected A a;
protected int id;
public A(A a, Integer id) {
this.a = a;
this.id = id;
public A(int id) { this.id = id; }
public void print() {
System.out.println("Class A called... from a " + a.getClass().getCanonicalName() + " using the original instance with id = " + a.id);
static class B extends A {
public B(A a, Integer id) { super(a, id); }
public B(int id) { super(id); }
public void print() { System.out.println("Class B called..."); }
static class C extends B {
public C(A a, Integer id) { super(a, id); }
public C(int id) { super(id); }
public void print() {
try {
System.out.println("Class C called...");
Object obj = getClass().getSuperclass().getSuperclass().getConstructor(A.class, Integer.class).newInstance(this, -111);
obj.getClass().getMethod("print", null).invoke(obj, null);
} catch (Exception e) {
e.printStackTrace();
}Anyway, I think that enables one to invoke overridden methods in super classes, regardless of how "high-up" they are in the class heirarchy (without having to use a new object to do it). Use that idea in an interview at your own risk but just not in interviews for the same position I am trying to get...
Edited by: dpxqb on Apr 17, 2010 4:43 AM -
Access super class private variables
class A
private int i,j;
A()
i=j=20;
public void show()
System.out.println(i+" "+j);
class B extends A
int k;
B()
super();
k=20;
public static void main(String args[])
B b=new B();
b.show();
In the above program, when a instance of class A is created, the memory is allocated for 2 private integer variables(i and j in this case) 8 byte of memory gets allocated and the referance is returned to the object.
ex:
A a=new A();
a contains the address of memory allocated for 2 integer variables.
In this code there is another class called B which contains only one variable of it's own.when a object is creted for class B only 4 byte of memory is allocated and the reference is returned.
ex:
B b=new B();
b contains address of 4 byte of memory allocated.
my doubt is when the B's constructor is called,it inturn calls super(),
where the variables are intialized. variable (i,j) does not exist in memory and how are they getting initialized.are they created at runtime and getting initialized.Though B has no explicit control over these variables it can able to access their values.How is that possible??Can you please stop creating multiple threads with the same question. There is already a discussion in your other thread. Please don't waste our time.
http://forum.java.sun.com/thread.jspa?messageID=4063146#4063146
Kaj -
Composition in java : how to access super-class from sub-class
I have 3 classes related by composition
class A{
B b = new B();
class B{
List<C> cList = new ArrayList<C>();
in class C{
getSample(){
//Try to access class A
how can I access A from class C ?
Any help is appreciated!well, 'Id' is known only to class A, and class C has a getSample() which is called in class A.
class A{
B b = new B();
getID(){
return id;
b.getC().getSample();
class B{
List<C> cList = new ArrayList<C>();
class C{
getSample(){
if() {
//pick up value from properties file
// format the value and parameter substitute it with 'Id' from A
The design does seem a little weird, but I guess this is the only way to do this considering the other constraints we have ....
TIA -
Hi,
If I have a Subclass that overrides a method in a superclass, is it possible to call that method from the superclass?
ThanksHi thanks for the reply, but that works for static methods, I'm trying to figure out non-static methods. Below, I want to call the method a() from the superclass using an instance of the subclass.
class superclassA
void a()
System.out.println("in method a");
class subclassA extends superclassA
void a()
System.out.println("in method b");
public class overtest
public static void main(String [] args)
subclassA sub = new subclassA();
superclassA.a();//non-static method a cannot be referenced from a static context
Thanks! -
How to access super class's super class
Hello every one.
I have a question.
if I have a class like:
public class A {
void methoda() {
void methodb() {
and a class B extends A and override A's methoda
public class B extends A {
void methoda() {
and a class C extends B which want use A's methoda.
public class C extends B {
// and here I want to use class A 's methoda,how can I do?
thanks a lotTry the following. When run it eill print out:
[In class C] A:B:C
Now calling A's method: [In class A] A and i is 500Which is what you want right?
public class TestSuperSuper {
public static void main (String[] args) throws Exception {
C c = new C();
c.setName("A", "B", "C");
c.setI(500);
c.methodA();
static class A {
String aName;
int i;
public void methodA(){
System.out.println("[In class A] " + aName + " and i is " + i);
public void setName(String aName){
this.aName = aName;
public void setI(int i){
this.i = i;
static class B extends A {
String bName;
public void methodA(){
System.out.println("[In class B] " + aName + ":" + bName);
public void setName(String aName, String bName){
this.aName = aName;
this.bName = bName;
static class C extends B {
String cName;
A wrappedA;
public C(){
wrappedA = new A();
public void methodA(){
reflectOnA();
System.out.println("[In class C] " + aName + ":" + bName + ":" + cName);
System.out.print("Now calling A's method: ");
wrappedA.methodA();
public void setName(String aName, String bName, String cName){
this.aName = aName;
this.bName = bName;
this.cName = cName;
private void reflectOnA(){
try {
Field[] aFields = wrappedA.getClass().getDeclaredFields();
for (int i = 0; i < aFields.length; i++){
Class fldType = aFields.getType();
if (fldType.isPrimitive()){
if (fldType.getName().equals("int")){
aFields[i].setInt(wrappedA, aFields[i].getInt(this));
else {
// now do the other primitive type tests here
else {
aFields[i].set(wrappedA, aFields[i].get(this));
catch (Exception e){
System.err.println(e);
The main thing here is that in class C you have an instance variable called wrappedA which is an instance of A and the method called reflectOnA(). Basically, what this method does is it will set all the fields in wrappedA to the same values that this object has so that it would look like that wrappedA is somewhat the same as this object. You will call this method whenever you want to call your superclass' superclass' method.
Hope this helps. -
Accessing a Sub class variable in a Super Class
Hi ,
Is there any easiest way to access a Subclass Variable in a Super Class.
Class Super1{
Class sub extends Super1
private String substring1;
In my application the 'substring1' values is not null .But all fields in Super1 class are null .
How can i access the value of the Subclass Variable in Super class .
ThanksThis would be a way to make the superclass dependent on subclass behavior. Of course this only makes sense if getSubString() is likely to have multiple different implementations in different subclasses.
public abstract class Super {
public String getString() {
return "SuperString" + getSubString();
protected abstract String getSubString();
public class Sub extends Super {
private String substring;
protected String getSubString() {
return substring;
}Using this just to access a variable whose contents differ from subclass to subclass is overkill. If you want each subclass to provide a different substring, create a constructor with a substring parameter in the superclass instead:public class Super {
private String substring;
protected Super(String substring) {
this.substring = substring;
public String getString() {
return "SuperString" + substring;
public class Sub extends Super {
public Sub() {
super("substring");
} -
Is there any way to access an overridden method of super class?
class Animals
void makeNoice(){System.out.println("General noice");}
class Dog extends Animals
void makeNoice(){System.out.println("bark");}
};Is there any way to access the makeNoice() of Animals class from a Dog object
Dog dog = new Dog();
Animal animaldog = dog;
animaldog.makeNoice(); // will always calls Dog's makeNoice() ie the overriden method.
Is there a way to access the Animals makeNoice() method ? by using cast or super etc?
Or it is not possible at all?Rajeebs wrote:
Now another question coming in my mind.
Whether any way to access a method which belong to super class's super class without using any method of class B,
like super.super.fn() ??Isn't this just the same question again? And won't you again just "solve" it by writing some invokeSuperSuperMethod or other? This flawed design is quickly getting out of hand, isn't it? The question isn't "How can I invoke an arbitrarily deep superclass' method?" but more "Why do I need to invoke a method belonging to a concrete type at all?". If you need to do that, chances are you've misused inheritance.
To use your initial sample code, in what circumstance would you require that a Dog make anything other than a Dog noise? It makes no sense. Point is, you have an Animal abstraction, and can call makeNoise on any instance of any subclass, and it will make the appropriate noise. By trying to use trickery to force other noises, you're doing something unnatural, and you're also depending on actual specific concrete subclasses. If you're going to go to specific classes and ask them to make their noise, what use is the inheritance? What use it the polymorphism?
Are we heading into another "I've got a brilliant idea for a [useless language feature|http://forums.sun.com/thread.jspa?threadID=5423706&messageID=10905772#10905772], guys!" thread? -
Private or Protected access for super class variables
What is the best practice...
Assume there is a class hierachy like
Person (Super class) / StaffMember/ Professor (Sub class)
1) The best way is to keep all the instance variables of each and every class private and access the private variables of super classes through subclass constructors (calling "super()")
Ex:-
public class Person {
private String empNo;
public Person (String empNo) {
this.empNo = empNo;
public class Professor extends Person {
private String ........;
private int ...........;
public Professor (String pEmpNo) {
super(pEmpNo);
OR
2)Changing the access level of the super class variables into "protected" or "default" and access them directly within the sub classes...
Ex:-
public class Person {
protected String empNo;
public Person () {
public class Professor extends Person {
String ........;
int ...........;
public Professor (String empNo) {
this.empNo = empNo;
Thank you...i'd think that you'd be better off relaying your initial values through the super class's constructor that way you'll get cleaner code, there's a possibly of inconsistency with option 2. i.e. you can then write code in your super classes to generally handle and properly initialize the instance variables while in the case of option 2, you'll have arbitrary constructors performing arbitrary initialization procedures
-
Error while calling a super class public method in the subclass constructor
Hi ,
I have code like this:
CLASS gacl_applog DEFINITION ABSTRACT.
PUBLIC SECTION.
METHODS:
create_new_a
IMPORTING pf_obj TYPE balobj_d
pf_subobj TYPE balsubobj
pf_extnumber TYPE string
EXPORTING pfx_log_hndl TYPE balloghndl
EXCEPTIONS error
ENDCLASS.
CLASS gacl_applog IMPLEMENTATION.
METHOD create_new_a.
DATA: ls_log TYPE bal_s_log.
Header aufsetzen
MOVE pf_extnumber TO ls_log-extnumber.
ls_log-object = pf_obj.
ls_log-subobject = pf_subobj.
ls_log-aluser = sy-uname.
ls_log-alprog = sy-repid.
ls_log-aldate = sy-datum.
ls_log-altime = sy-uzeit.
ls_log-aldate_del = ls_log-aldate + 1.
CALL FUNCTION 'BAL_LOG_CREATE'
EXPORTING
i_s_log = ls_log
IMPORTING
e_log_handle = pfx_log_hndl
EXCEPTIONS
OTHERS = 1.
IF ( sy-subrc NE 0 ).
MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4
RAISING error.
ENDIF.
ENDMETHOD.
CLASS gcl_applog_temp DEFINITION INHERITING FROM gacl_applog.
PUBLIC SECTION.
DATA: log_hndl TYPE balloghndl READ-ONLY
, t_log_hndl TYPE bal_t_logh READ-ONLY
METHODS: constructor
IMPORTING pf_obj TYPE balobj_d
pf_subobj TYPE balsubobj
pf_extnumber TYPE string
EXCEPTIONS error
, msg_add REDEFINITION
, display REDEFINITION
ENDCLASS.
CLASS gcl_applog_temp IMPLEMENTATION.
METHOD constructor.
CALL METHOD create_new_a
EXPORTING pf_obj = pf_obj
pf_subobj = pf_subobj
pf_extnumber = pf_extnumber
IMPORTING pfx_log_hndl = log_hndl.
IF ( sy-subrc NE 0 ).
MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4
RAISING error.
ENDIF.
ENDMETHOD.
A public method of Super class has been called from the constructor of the sub class. we are getting the syntax error :
' In the constructor method, you can only access instance attributes, instance methods, or "ME" after calling the constructor of the superclass '
Can you please suggest how to change the code with out affecting the functioanlity.
Thank you ,
Lakshmi.Hi,
Call that method by instance of Subclass. OR
SUPER-->method.
Read very useful document
Constructors
Constructors are special methods that cannot be called using CALL METHOD. Instead, they are called automatically by the system to set the starting state of a new object or class. There are two types of constructors - instance constructors and static constructors. Constructors are methods with a predefined name. To use them, you must declare them explicitly in the class.
The instance constructor of a class is the predefined instance method CONSTRUCTOR. You declare it in the public section as follows:
METHODS CONSTRUCTOR
IMPORTING.. [VALUE(]<ii>[)] TYPE type [OPTIONAL]..
EXCEPTIONS.. <ei>.
and implement it in the implementation section like any other method. The system calls the instance constructor once for each instance of the class, directly after the object has been created in the CREATE OBJECT statement. You can pass the input parameters of the instance constructor and handle its exceptions using the EXPORTING and EXCEPTIONS additions in the CREATE OBJECT statement.
The static constructor of a class is the predefined static method CLASS_CONSTRUCTOR. You declare it in the public section as follows:
CLASS-METHODS CLASS_CONSTRUCTOR.
and implement it in the implementation section like any other method. The static constructor has no parameters. The system calls the static constructor once for each class, before the class is accessed for the first time. The static constructor cannot therefore access the components of its own class.
Pls. reward if useful.... -
Problem with Dynamically accessing EJB Class objects in WL 7.0 SP1
I am trying to build a component which has the ability to instantiate and execute
an known EJB method on the fly.
I have managed to build the component but when I try and execute it I get a ClassNotFoundException.
I know that the EJB I am trying to invoke is deployed and available on the server,
as I can see it in the console, I also seen to have been able to get the remote
interface of the object, my problem occurs when I try and access the class object
so I can perform a create on the object and then execute my method
The code I have written is below:
private Object getRemoteObject(Context pCtx, String pJNDIName, String pHomeBean)
throws Exception {
String homeCreate = "create";
Class []homeCreateParam = { };
Object []homeCreateParamValues = {};
try {
//This call seems to work and doesn't throw an exception
Object home = pCtx.lookup(pJNDIName);
//However this call throws a java.lang.ClassNotFoundException
Class homeBean = Class.forName(pHomeBean);
Method homeCreateMethod = homeBean.getMethod(homeCreate,homeCreateParam);
return homeCreateMethod.invoke(home, homeCreateParamValues);
} catch (NamingException ne) {
logStandardErrorMessage("The client was unable to lookup the EJBHome.
Please make sure ");
logStandardErrorMessage("that you have deployed the ejb with the JNDI
name "+pJNDIName+" on the WebLogic server ");
throw ne;
} catch (Exception e) {
logStandardErrorMessage(e.toString());
throw e;
Any advice would be really appreciated, I'm fast running out of ideas, I suspect
it has something to do with the class loader but I'm not sure how to resolve it
Regards
Jo CorlessHello Joanne,
Congratulations! I'm very happy that you've managed to fix your problem. It's
always essential to understand how to package applications when deploying on BEA
WebLogic. Usually, by throwing everything into an EAR file solves just about all
the class loader problems. :-) Let us know if you have any further problems that
we can assist you with.
Best regards,
Ryan LeCompte
[email protected]
http://www.louisiana.edu/~rml7669
"Joanne Corless" <[email protected]> wrote:
>
>
I've fixed it!!!!!!!!
Thanks to everyone who gave me help!!!!
The class loader was the culprit which is what I suspected all along.
As soon
as I put the 2 jar files I was using into an EAR file the problem went
away!!!!!
Thanks again
Jo Corless
"Ryan LeCompte" <[email protected]> wrote:
Hello Joanne,
As Mr. Woollen mentioned, I also believe it's a problem with the class
loader.
You need to be careful how you arrange your EJBs, because WebLogic has
a specific
method in which it loads classes in an EAR, JAR, and WAR file(s). Please
refer
to http://dev2dev.bea.com/articles/musser.jsp for more information about
BEA WebLogic
class loading mechanisms and caveats. Also, try printing out the various
methods
that are available on the object that was returned to you via reflection.
For
example, use the getMethods() method, which returns an array of Method
objects
that you can subsequently cycle through and print out the various method
names.
This way you can discover if the class found/returned to you is indeed
the one
you intend to locate.
Hope this helps,
Ryan LeCompte
[email protected]
http://www.louisiana.edu/~rml7669
Rob Woollen <[email protected]> wrote:
I believe the issue is the home interface class for this EJB is not
available in the class loader which is doing the reflection.
If you do:
getClass().getClassLoader().loadClass(homeInterfaceClassName)
I suspect it will fail. Reflection still requires that the class be
loadable.
-- Rob
Joanne Corless wrote:
Hi Slava,
If I make my code look like you describe below I get a compliationerror telling
me that
home.getMethod() is not recognised (no such method)
If I change it slightly and use
Method homeCreateMethod =
home.getClass().getMethod(homeCreate,homeCreateParam);
The code will compile OK but when executed it still throws a NoSuchMethodException
Any ideas ?
Thanks for your help so far
Regards
Jo Corless
Your code should look like
Object home = pCtx.lookup(pJNDIName);
Method homeCreateMethod =
home.getMethod(homeCreate,homeCreateParam);
return homeCreateMethod.invoke(home, homeCreateParamValues);
Regards,
Slava Imeshev
"Joanne Corless" <[email protected]> wrote in message
news:[email protected]...
Hi Ryan,
I also wanted to mention that if you do a "header search" in this
particular
newsgroup
with the search query as "reflection", you will see many previousmessages
regarding
reflection and EJBs. I believe you could learn a lot from thedifficulties
that
others have faced and solved.I tried that and although there was a number of similar cases noneof them
actually
seem to fix my issue. Thanks for the suggestion though
Are the EJBs that you are trying to access accessible via your
system
classpath?
Try to avoid having them accessible via the main system classpath,and
only bundle
them in your appropriate EJB jar files (contained in an EAR file,for
example).Maybe I should have laid the problem out a little clearer.
I have a number of EJB's bundled up in a JAR file which is hot deployedto
the
server. Within this first JAR file is an EJB (SSB) component that
needs
to
be
able to invoke a known method on another EJB. This second EJB may
or
may
not be
within the first JAR file but it also will be hot deployed.
The component trying to invoke the method on the 2nd EJB has to
be
able to
create
an instance of the 2nd EJB without actually knowing anything bar
a
JNDI
Name which
is passed in at runtime.
I can get as far as doing the
Object home = pCtx.lookup(pJNDIName);
This returned a class with the name
"com.csc.edc.projects.allders.httppostoffice.postman.PostmanBean_mp8qy2_Home
Impl_WLStub"
My problem seems to occur when I try and invoke the create method
Method homeCreate = home.getClass().getMethod("create", new Class[0]);
My code throws a java.lang.NoSuchMethodException at this point so
I
am
unable
to progress to the next step of :
Object bean = homeCreate.invoke(home, null);
So I can return the instantiated bean back to the calling client.
Why am I getting the NoSuchMethodException, is is because I am gettinga
stub
back rather than the home interface and if so how do I get the truehome
interface
from the bean
Thanks in advance
Jo Corless -
How to inherit super class constructor in the sub class
I have a class A and class B
Class B extends Class A {
// if i use super i can access the super classs variables and methods
// But how to inherit super class constructor
}You cannot inherit constructors. You need to define all the ones you need in the subclass. You can then call the corresponding superclass constructor. e.g
public B() {
super();
public B(String name) {
super(name);
} -
Calling the super class method from the subclass
Hi all,
I have a question about inheritence and redefinition of methods. Is it possible to call the superclass implementation of a method which is redefined in the subclass in another method of the subclass?There are possbilities like creation of an explicit super class instance or delegating the super class method implementation to another method which is also protected etc. What i mean is, is there a direct way of calling it?We have ,me, as the reference for the instance we have(which is the subclass instance in this case), is there also a way of pointing the superclass implementation(with super we can reference in the subclass redefinition, my question is if we have such a parameter in other methods of the subclass too)
Thanks in advance
SukruHi,
The super reference can only be used in redefined methods to call superclass implementation . So probably what you can do is use upcasting and access the required superclass implementation. I can think of only this way...;-)
Ex data lr_super type ref to cl_superclass
lr_super = lr_subclass.
lr_super->method().
~Piyush Patil -
Is it possible to OVERLOAD a super-class method in a sub-class?
Hi all,
I have a query that
Is it possible to OVERLOAD a super-class method in a sub-class?
If it is possible, please give me an example.
Thanks,
HariHi,
Is the method int Display(int a){} overloading
the super-class's void Display() method? If
possible, please clarify this and how it would be
method overloading?
hanks,
Hari
Hi Hari,
Yes, it is possible. Look at this piece of code:
class Senior
void Display()
System.out.println("Super class method");
class Junior extends Senior
int Display(int a)
System.out.println("Subclass method: "+a);
return(a+10);
}> }
class example
public static void main(String args[])
Junior j = new Junior();
j.Display();
System.out.println("Subclass method
od "+j.Display(5));
Is this what you were asking? Hope this helped.Hi,
I guess you guys are confused here...
Overloading is achieved by methods in the same class...
Overriding is across a superclass subclass methds.
Maybe you are looking for
-
It seems not possible to create this kind of "Brush" in Photoshop CS6, can anyone help?
I found this website. http://newhive.com/andrew/drawonme?q=%23All%2F And I thought this "brush" is a really cool technique for fast sketches. But it does not seem possible in photoshop, does it? I tested it with CS5 and even the new CS6 Brushes. Tha
-
I must be doing something wrong. I can not see the other computer (eMac). The eMac connects to Airport and the net. I have the eMac running 10.4.5 with no firewall and personal file sharing turned on.
-
Simple Calculations - Any Samples out there?
I've created a simple form with inputs for Cost & Profit. I added two fields for Percent Profit and Price but want those to be calculated from the Cost and Profit entries. The calculation is simple and would be a no brainer in Excel, but I can't figu
-
Background of macbook pro not working
I plugged my macbook pro into a tv via a HDMI cord to watch a movie. When I unplugged it, 1/4 of my background display is the galaxie background image that is on the tv when the computer gets plugged into it. I've tried to change the background/displ
-
Usability: the Synchronize Preview window is too tall for my 12-inch PB screen
When not working in front of my larger monitor, I have trouble with Dreamweaver CS3 when attempting to synchronize local files to either my remote site or my testing server. After I tell the program to compare the local files to the remote ones, and