Regarding Inheritance (and super)

Let:
class A { ... }
class B extend A { ... }
From within class B, the super keyword allows me to access the visible methods and variables in A. However, super does not seem to be a reference; that is, while I can legally do
Object a = this;
I cannot do
Object a = super;
But, I would really like to be able to do this. That is, from the context of B, I would like to obtain a reference to the supertype, such that (ref instanceof A == true), (ref instanceof B == false). In short, I want a 'super' that behaves exactly like a 'this'. The ultimate goal of this is to pass a reference to the supertype into a method (say, a static method). Is this at all possible in Java? My only idea at the moment is to create a new instance of the superclass and set all of its state correctly, pass this instance into the desired method, then reestablish state once the method returns. Sounds painful and error-prone, though.
Thanks for any ideas.

sancho_panza wrote:
ejp wrote:
Why? Any method will already accept a reference to B as a reference to A, if B extends A.I am performing a transformation on Java classes that involves turning instance methods into static methods. It is not problem to pass a reference to 'this' into such a static method. But what if the instance method invokes super? Super cannot be invoked statically; thus I would like to pass 'super' into this method, which is impossible. I suppose creating a temporary container for the superclass is the easiest way (though it seems like this should be a lot easier).To do this you need to transform the Java static inheritance to a dynamic equivalent. This is quite straightforward. Say you have,
class A {}
class B extends A {}Now the A class is split into an interface A and an implementation class A_IMPL. You get this,
interface A {}
class A_IMPL implements A {}
class B implements A {
   private A a_ref = new A_IMPL(); // object holding implementation of A
   // The implementation of inherited A methods is delegated to the A_IMPL object
}In the above a_ref is the super reference you desired.

Similar Messages

  • Multiple inheritance and super

    How to I get to a super function when using multiple inheritance? For example, the code below doesn't compile if Human extends Job, but works fine if Human only extends Animal.
    package test;
    import java.lang.System;
    public class Job {
    public class Animal {
    public attribute isStanding:Boolean = false;
    public function printStatus():Void {
    System.out.println( if (isStanding) "Standing up" else "Laying down");
    public class Human extends Animal, Job {
    public attribute isAtWork:Boolean = false;
    public function printStatus():Void {
    System.out.println( if (isAtWork) "At the office" else "At home");
    super.printStatus();
    var person:Human = Human{};
    person.printStatus();

    Thanks! Works great. I never even tried that since my brain is wired to only use that syntax for calling a static method/function/field.
    Note: If you change the class definition in the original sample from
    public class Human extends Animal, Job {topublic class Human extends Animal {The original compiles and runs as you'd expect. So the 'super' keyword exists in some form and has the expected result for singular inheritance when used to call parent methods. I think you are thinking of using it to call constructors. In that usage I think you are right that it doesn't work at all in JavaFX.

  • Inheritance and super usage help

    so i have a parent class called Gun and i have a protected field called bulletsInGun in the constructor and then i have a a subclass called HandGun that inherits from the Gun class and i am trying to used the field bulletsInGun in the parents class constructor for the HandGun subclass constructor. how would i do that? i tried super.bulletsInGun and i tried super(bulletsInGun) and none of them work i keep getting "not a statement error".

    this is my gun class the parent class
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package javaapplication1;
    * @author steven
    abstract public class Gun {
        private int numberOfBulletsAllowedInGun;
        private int bulletsInGun;
        protected static final int NUMBEROFBULLETSMAX = 0;
        public Gun()
            numberOfBulletsAllowedInGun= 0;   
            bulletsInGun = 0;
         * this method should reload the bullet.
        public void shoot()
            if(bulletsInGun <= 0)
            cannotFire();
            else
                typeOfShotInitated();
        public void cannotFire(){
            System.out.println("No, more bullets cannot fire must reload.");
       abstract public void typeOfShotInitated();
       abstract public void reload();
    }this is the subclass that inheritances from the gun class
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package javaapplication1;
    * @author steven
    public class HandGun extends Gun{
                /*how do i bring in "protected static final int NUMBEROFBULLETSMAX = 0;" from the parent class into each of the subclasses that i make? */
        public HandGun(){
            super(bulletsInGun);                                   // how do i add these fields from the Gun class?
            super(numberOfBulletsAllowedInGun);         //
        public void reload(){
            if(bulletsInGun == )
            bulletsInGun += 9;
        public void typeOfShotInitated(){
    }

  • Inheriting and the "super" keyword

    I found a case where "super" is not working as I understand it should...
    Can someone explain me the underlying theory that makes JAVA behave this way??
    public class Base {
         public void method1() {
              System.out.println("method1 from \"Base\" class. About to call method2.");
              method2();
         public void method2() {
              System.out.println("method2 from \"Base\" class. About to call method3.");
              method3();
         public void method3() {
              System.out.println("method3 from \"Base\" class.");
    public class Extension extends Base {
         @Override
         public void method1(){
              System.out.println("method1 from \"Extension\" class. About to call super.method2.");
              super.method2();          
         @Override
         public void method2(){
              System.out.println("method2 from \"Extension\" class. About to call method3.");
              method3();          
         @Override
         public void method3(){
              System.out.println("method3 from \"Extension\" class.");                    
    public class Main {
         public static void main(String args[]) {
              System.out.println("In \"The Java Programming Language,\n" +
                        "Fourth Edition By Ken Arnold, James Gosling, David Holmes\"\n"+
                        "chapter: 3.3: \"Inheriting and Redefining Members\""+
                        " says:");
              System.out.println("Using super is the only case in which the type of\n" +
                        "the reference governs selection of the method implementation\n" +
                        "to be used. An invocation of super.method always uses the\n" +
                        "implementation of method the superclass defines (or\n" +
                        "inherits). It does not use any overriding implementation of\n" +
                        "that method further down the class hierarchy.\n");
              System.out.println("But by running this code, i get:");
              System.out.println("------------------------------------------");          
              Extension ext = new Extension();
              ext.method1();          
              System.out.println("------------------------------------------");
              System.out.println("\nWHY??? I was expecting:\n"+
                        "method1 from \"Extension\" class. About to call super.method2.\n" +
                        "method2 from \"Base\" class. About to call method3.\n" +
                        "method3 from \"Base\" class.");          
    THANKS!!

    IgnacioKriche wrote:
    But I used "super", so this means to use the methods of the super class and I understand that a method called within another, is part of this last one. this is:
    if inside method 'x', method 'y' is called, then 'y' is part of 'x' . Agree? And therefore since I am using super I'm saying use 'x' method from super class since 'y' is part of 'x' then super applies for 'y' as well so what is method from the extended class doing here? It's like we have a mix between the 'x' from super and 'y' from the extended. Something like super only applies for the first level not at a deeper level (a method called from another)No. Just because the base class method2() invokes method3() does NOT mean it will always invoke base's version of method3. If it did that, then polymorphism would definitely be broken.
    You explicitly invoked super.method2(), so that told the compiler to explicitly use the base class version of that method. But then method2 in the base class invokes method3(). That ends up invoking the overridden version in the subclass, by design, because afterall the actual object whose methods are being executed is a subclass instance. If it didn't do that, then polymorphism would be broken for everyone else.
    If you think you need the behavior you are looking for, you are just designing it wrong in the first place.

  • Question regarding selectOneMenu and PROCESS_VALIDATIONS(3) phase

    Hi im a bit lost regarding selectOneMenu and how validation phase all works together.
    The thing is that i have a simple selectOneMenu
    <h:form id="SearchForm">                                                  
         <h:panelGrid columns="3"  border="0">
              <h:outputLabel id="caseTypeText" value="#{msg.searchCaseCaseType}" for="caseType" />                         
              <h:selectOneMenu id="caseType" value="#{searchCaseBean.caseType}" style="width: 200px;" binding="#{searchCaseBean.caseTypeSelect}">     
                   <f:selectItem itemValue="" itemLabel="#{msg.CommonTextAll}" />                                             
                   <f:selectItems value="#{searchCaseBean.caseTypes}"  />                              
              </h:selectOneMenu>
              <h:message for="caseType" styleClass="errorMessage" />
              <h:panelGroup />
              <h:panelGroup />
              <h:commandButton action="#{searchCaseBean.actionSearch}" value="#{msg.buttonSearch}" />
         </h:panelGrid>
    </h:form>Now when i hit submit button i can see that the bean method searchCaseBean.caseTypes (used in the <f:selectItems> tag) is executed in the PROCESS_VALIDATIONS(3) phase. How come? I dont whant this method to be executed in phase 3, only in phase 6.
    If i add the this in the method if (FacesContext.getCurrentInstance().getRenderResponse())
    public List<SelectItem> getStepStatuses(){
         List<CaseStep> caseSteps = new ArrayList<CaseStep>();
         if (FacesContext.getCurrentInstance().getRenderResponse()) {
              caseSteps = getCaseService().getCaseStep(value);     
         List<SelectItem> selectItems = new ArrayList<SelectItem>(caseSteps.size());
         for(int i=0; i < caseSteps.size(); i++){
              CaseStep step = caseSteps.get(i);               
              String stepStatus = step.getStatus() + "_" + step.getSubStatus();           
              selectItems.add(new SelectItem(stepStatus, step.getShortName()));
         return selectItems;
    } Now i get a validation error (javax.faces.component.UISelectOne.INVALID) for the select field and only phase1, phase2, phase 3 and phase 6 is executed.
    Im lost?

    I see. Many thanxs BalusC. Im using your blog very often, and its very helpfull for me.
    I changed now to use the constructor load method instead. But know im getting problem of calling my service layer (Spring service bean). Its seems they havent been init when jsf bean is calling its constructor.
    Can i init the spring service bean from the faces-config file?
    JSF Bean
        public SearchCaseBean() {
              super();
                    //caseService need to be init
              if(getCaseService() == null){
                   setCaseService((CaseService)getWebApplicationContextBean("caseService"));
              fillCaseTypeSelectItems();
              fillCaseStatusSelectItems();
    .....faces-config
    <managed-bean>
              <managed-bean-name>searchCaseBean</managed-bean-name>
              <managed-bean-class>portal.web.SearchCaseBean</managed-bean-class>
              <managed-bean-scope>request</managed-bean-scope>          
              <managed-property>
                   <property-name>caseService</property-name>
                   <value>#{caseService}</value>
              </managed-property>
         </managed-bean>

  • Question regarding Inheritance.Please HELP

    A question regarding Inheritance
    Look at the following code:
    class Tree{}
    class Pine extends Tree{}
    class Oak extends Tree{}
    public class Forest{
    public static void main(String args[]){
      Tree tree = new Pine();
      if( tree instanceof Pine )
      System.out.println( "Pine" );
      if( tree instanceof Tree )
      System.out.println( "Tree" );
      if( tree instanceof Oak )
      System.out.println( "Oak" );
      else System.out.println( "Oops" );
    }If I run this,I get the output of
    Pine
    Oak
    Oops
    My question is:
    How can Tree be an instance of Pine.? Instead Pine is an instance of Tree isnt it?

    The "instanceof" operator checks whether an object is an instance of a class. The object you have is an instance of the class Pine because you created it with "new Pine()," and "instanceof" only confirms this fact: "yes, it's a pine."
    If you changed "new Pine()" to "new Tree()" or "new Oak()" you would get different output because then the object you create is not an instance of Pine anymore.
    If you wonder about the variable type, it doesn't matter, you could have written "Object tree = new Pine()" and get the same result.

  • Regarding inheritance in adobe day cq

    Hi,
    I am fairly new to adobe cq...
    I came across inheritance in the documentation....I did not understand the difference between disable inheritance and cancel inheritance....
    I applied disable inheritance but the child pages still inherited the parent page images which was put in the inherited paragraphs.....
    Could anyone please help me...
    Thanks in advance...
    Regards,
    Heidi

    HI Heidi,
      I beleive your understanding is correct & agree the name is slight confusing This difference is not clear however reading the label descriptions of the checkbox carefully will help to clear configuration.  Documentation at [1].
    Just to demonstrate let us use geometrixx example. In author instance
    *    Go to http://<host>:<port>/content/geometrixx/en/products/triangle.html
    *    On the right side you would see iparasys, Select "Cancel Inheritance" & save.
    *    Go to http://<host>:<port>/content/geometrixx/en/products/triangle/overview.html
    *    You would see it is not inherited & if you are in edit mode you would see "Parent canceled inheritance"
    For second case
    *    Go to http://<host>:<port>/content/geometrixx/en/products/square.html
    *    In Iparasys Select "Disable Inheritance" & save.
    *    IN edit mode you would see "Inheritance disabled" & in preview mode not inherited from the parent page.
    [1]   http://dev.day.com/docs/en/cq/current/wcm/default_components.html#Inheritance%20Paragraph% 20System%20%28iparsys%29
    Thanks,
    Sham

  • A question about inheritance and overwriting

    Hello,
    My question is a bit complicated, so let's first explain the situation with a little pseudo code:
    class A {...}
    class B extends A{...}
    class C extends B {...}
    class D extends C {...}
    class E extends B {...}
    class F {
      ArrayList objects; // contains only objects of classes A to E
      void updateObjects() {
        for(int i = 0; i < objects.size(); i++)
          A object = (A) objects.get(i); // A as superclass
         update(A);
      void update(A object) { ... }
      void update(B object) { ... }
      void update(D object) { ... }
    }My question now:
    For all objects in the objects list the update(? object) method is called. Is it now called with parameter class A each time because the object was casted to A before, or is Java looking for the best fitting routine depending on the objects real class?
    Regards,
    Kai

    Why extends is evil
    Improve your code by replacing concrete base classes with interfaces
    Summary
    Most good designers avoid implementation inheritance (the extends relationship) like the plague. As much as 80 percent of your code should be written entirely in terms of interfaces, not concrete base classes. The Gang of Four Design Patterns book, in fact, is largely about how to replace implementation inheritance with interface inheritance. This article describes why designers have such odd beliefs. (2,300 words; August 1, 2003)
    By Allen Holub
    http://www.javaworld.com/javaworld/jw-08-2003/jw-0801-toolbox.html
    Reveal the magic behind subtype polymorphism
    Behold polymorphism from a type-oriented point of view
    http://www.javaworld.com/javaworld/jw-04-2001/jw-0413-polymorph_p.html
    Summary
    Java developers all too often associate the term polymorphism with an object's ability to magically execute correct method behavior at appropriate points in a program. That behavior is usually associated with overriding inherited class method implementations. However, a careful examination of polymorphism demystifies the magic and reveals that polymorphic behavior is best understood in terms of type, rather than as dependent on overriding implementation inheritance. That understanding allows developers to fully take advantage of polymorphism. (3,600 words) By Wm. Paul Rogers
    multiple inheritance and interfaces
    http://www.javaworld.com/javaqa/2002-07/02-qa-0719-multinheritance.html
    http://java.sun.com/docs/books/tutorial/java/interpack/interfaceDef.html
    http://www.artima.com/intv/abcs.html
    http://www.artima.com/designtechniques/interfaces.html
    http://www.javaworld.com/javaqa/2001-03/02-qa-0323-diamond_p.html
    http://csis.pace.edu/~bergin/patterns/multipleinheritance.html
    http://www.cs.rice.edu/~cork/teachjava/2002/notes/current/node48.html
    http://www.cyberdyne-object-sys.com/oofaq2/DynInh.htm
    http://www.gotw.ca/gotw/037.htm
    http://www.javajunkies.org/index.pl?lastnode_id=2826&node_id=2842
    http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=1&t=001588
    http://pbl.cc.gatech.edu/cs170/75
    Downcasting and run-time
    http://www.codeguru.com/java/tij/tij0083.shtml
    type identification
    Since you lose the specific type information via an upcast (moving up the inheritance hierarchy), it makes sense that to retrieve the type information ? that is, to move back down the inheritance hierarchy ? you use a downcast. However, you know an upcast is always safe; the base class cannot have a bigger interface than the derived class, therefore every message you send through the base class interface is guaranteed to be accepted. But with a downcast, you don?t really know that a shape (for example) is actually a circle. It could instead be a triangle or square or some other type.
    To solve this problem there must be some way to guarantee that a downcast is correct, so you won?t accidentally cast to the wrong type and then send a message that the object can?t accept. This would be quite unsafe.
    In some languages (like C++) you must perform a special operation in order to get a type-safe downcast, but in Java every cast is checked! So even though it looks like you?re just performing an ordinary parenthesized cast, at run time this cast is checked to ensure that it is in fact the type you think it is. If it isn?t, you get a ClassCastException. This act of checking types at run time is called run-time type identification (RTTI). The following example demonstrates the behavior of RTTI:
    //: RTTI.java
    // Downcasting & Run-Time Type
    // Identification (RTTI)
    import java.util.*;
    class Useful {
    public void f() {}
    public void g() {}
    class MoreUseful extends Useful {
    public void f() {}
    public void g() {}
    public void u() {}
    public void v() {}
    public void w() {}
    public class RTTI {
    public static void main(String[] args) {
    Useful[] x = {
    new Useful(),
    new MoreUseful()
    x[0].f();
    x[1].g();
    // Compile-time: method not found in Useful:
    //! x[1].u();
    ((MoreUseful)x[1]).u(); // Downcast/RTTI
    ((MoreUseful)x[0]).u(); // Exception thrown
    } ///:~
    As in the diagram, MoreUseful extends the interface of Useful. But since it?s inherited, it can also be upcast to a Useful. You can see this happening in the initialization of the array x in main( ). Since both objects in the array are of class Useful, you can send the f( ) and g( ) methods to both, and if you try to call u( ) (which exists only in MoreUseful) you?ll get a compile-time error message.
    If you want to access the extended interface of a MoreUseful object, you can try to downcast. If it?s the correct type, it will be successful. Otherwise, you?ll get a ClassCastException. You don?t need to write any special code for this exception, since it indicates a programmer error that could happen anywhere in a program.
    There?s more to RTTI than a simple cast. For example, there?s a way to see what type you?re dealing with before you try to downcast it. All of Chapter 11 is devoted to the study of different aspects of Java run-time type identification.
    One common principle used to determine when inheritence is being applied correctly is the Liskov Substitution Principle (LSP). This states that an instance of a subclass should be substitutible for an instance of the base class in all circumstances. If not, then it is generally inappropriate to use inheritence - or at least not without properly re-distributing responsibilities across your classes.
    Another common mistake with inheritence are definitions like Employee and Customer as subclasses of People (or whatever). In these cases, it is generally better to employ the Party-Roll pattern where a Person and an Organization or types of Party and a party can be associated with other entities via separate Role classes of which Employee and Customer are two examples.

  • Java Inheritance and Types

    Hello,
    I have some super/sub classes, listed as follows:
    UnitMgr
    SpecialUnitMgr (child of UnitMgr)
    Unit
    SpecialUnit (child of Unit)
    I'm designing a lot inventory system where my SpecialUnitMgr applet will have many instances of Unit. Right now I have the system set up so that UnitMgr contains an instance var declared as "Unit aUnit;". UnitMgr as a parent class, takes care of common code between the many different UnitMgr child classes.
    Right now I have SpecialUnitMgr setup to use the inherited parent/super variable aUnit, and I have extended the functionality of Unit with SpecialUnit (added more instance vars, etc). I wish to use extended features of SpecialUnit within my SpecialUnitMgr class, but I am unable to do so because of type conflicts (i.e. i cant access SpecialUnit vars or methods from the instance aUnit because it is declared as Unit in UnitMgr).
    I want to keep a single instance of Unit or SpecialUnit going, but I'm not sure how to do so.
    I am wondering how to get around this problem, do I use Reflection? Is my design bad? I am trying to maintain the super classes as a core package.
    Jeff

    If I understand the problem correctly, you want generics. public class UnitMgr<U extends Unit>
        protected U aUnit;
    public class SpecialUnitMgr extends UnitMgr<SpecialUnit>
    }See http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html for more on generics.

  • Sanity test between SAP DOE and SUP

    Dear forum members,
    We are in the process of deploying Sybase Mobile application for SAP CRM. In this process, we have been able to install the relevant binaries in the landscape.
    We want to do a sanity test between DOE and SUP to ensure that connection is intact between two systems. Is there any mechanism to do this ?
    In the other thread, Siva informed that testing connection via SCC might not give proper results. It states as " Connection failed", but that is because of ESDMA incompatibility versioning.
    Regards,
    Viju

    HI,
    SCC most often informs correctly where the error could be. Sometimes it is just a hint as to where to look. This feature in SCC uses a new interface introduced in SP04.
    So if you are not yet upgraded to Mobile Gateway 1.1 SP04, unfortunately this Test connection will not work for you from SCC>
    If you are already on SP04, then login to DOE, goto "sdoe_esdma_design", select your cRM smartphone ESDMA, edit it and change the interface version to "14". regenerate the ESDMA, Download the ESDMA and redeploy the newly generated ESDMA Bundle to SUP server. Then try the Test connection again and it should tell you what else could be a problem if any.
    Hope this helps
    thanks
    shobha

  • Difference between roles Administrator and Super admin

    Dear Portal Gurus,
    Pls let me know the difference between
    roles Administrator and Super admin
    Thanks.
    Jack

    Hi Jack,
    The Administrator is the role that has all the rights that includes J2ee engine rights too but an superadmin is the one that has the role to the three admin roles that are
    Content Admin
    User Admin
    System Admin
    THIS IS THE BASIC DIFFERENCE BETWEEN SUPERADMIN AND ADMINISTRATOR.
    PS:Reward Point Please
    Regards,
    Naveen Gupta

  • The "always allow" button is grayed out in settings regarding cookies, and I can not find where to change the setting.  (Restrictions are not on.)

    The "always allow" button is grayed out in settings regarding cookies, and I can not find where to change the setting.  (Restrictions are not on.)  Do you know where I go to change the setting to allow me to "always allow" cookies?

    Hi lisaarnett111,
    If you are having issues turning on Always Allow for cookies in Safari on your iPad, you may want to check to make sure that you don't have Private Browsing enabled, as noted in the following article:
    Turn Private Browsing on or off on your iPhone, iPad, or iPod touch - Apple Support
    Regards,
    - Brenden

  • Difference between inheritance and abstract class

    difference between inheritance and abstract class

    See this thread:
    http://forum.java.sun.com/thread.jspa?forumID=24&threadID=663657
    And before Post New Topic, just search in this forums. All most will get answers.

  • Question regarding roaming and data usage

    I am currently out of my main country of service, and as such I have a question regarding roaming and data usage.
    I am told that the airplane mode is sufficient from keeping the phone off from roaming, but does this apply to any background data usage for applications and such?
    If the phone is in airplane mode, are all use of the phone including wifi and application use through the wifi outside of all extra charges from roaming?

    Ann154 wrote:
    If you are getting charged to use the wifi, then it is possible.  Otherwise no
    Just to elaborate here, Ann154 is referring to access charges for wifi, which is nothing to do with Verizon, so if you are using it in a plane, hotel, an internet cafe etc that charges for Wifi rather than being free .   Verizon does not charge you (or indeed know about!) wifi usage, or any other usage that is not on their cellular network (such as using a foreign SIM for example in global phones)  So these charges, if any, will not show up on the verizon bill app.  Having it in airplane mode prevents all cellular data traffic so you should be fine

  • Question regarding MM and FI integration

    Hi Experts
    I have a question regarding MM and FI integration
    Is the transaction Key in OMJJ is same as OBYC transaction key?
    If yes, then why canu2019t I see transaction Key BSX in Movement type 101?
    Thanks

    No, they are not the same.  The movement type transaction (OMJJ) links the account key and account modifier to a specific movement types.  Transaction code (OBYC) contains the account assignments for all material document postings, whether they are movement type dependent or not.  Account key BSX is not movement type dependent.  Instead, BSX is dependent on the valuation class of the material, so it won't show in OMJJ.
    thanks,

Maybe you are looking for