Super class variables

This is the situation:
abstract Class NiftySuperClass
    int anInteger;
    NiftySuperClass(int someArgument)
        // do something with someArgument. Not important.
public class SubClass extends NiftySuperClass
    SubClass(int someArgument)
        super(someArgument);
        anInteger = 100; //This is the important thing
    public int getAnInteger()
        return anInteger;
}Now, let's say that I create an instance of the SubClass and assign the result of getAnInteger() to a variable...
SubClass sc = new SubClass(15);
int anotherInteger = sc.getAnInteger();For some reason, it seems as if anotherInteger is assigned the value zero (0). Which would make perfect sense to me, of course, had I not initialized the variable in the constructor of the subclass. As it is written, though, I really would expect getAnInteger() to return 100. Please explain, if possible, why I should not expect it to do so.
And yes, I would expect a zero result if I had an integer variable called anInteger in the SubClass, and did something like this (since the variable would be determined by the kind of reference, sorta):
NiftySuperClass sc = new SubClass(15);
int anotherInteger = sc.getAnInteger();However, the variable in question comes from the SuperClass, and that (according to my own logic, at least) is assigned the value 100 in the constructor in the subclass. Hmm. Hope you follow me.
Thanks in advance,
smorgasbord

Either you are doing something you haven't told us, or you have a bug in your compiler or JVM. Could you post a small but complete, compilable and executable example?
The code you have posted is clearly not the code you are executing (as it wouldn't compile). When posting code to the forums, please create and test a complete example and then cut and paste the code (and preview it before posting).

Similar Messages

  • 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

  • Weird one..  i can't return a variable from the extended to the super class

    Hey everyone, i hope i'm not annoying you guys :)
    So today's problem is to return a variable (int) from a method of the extended class and print it ont the super class.
    I'm just testing the super class , if it works fine.
    So the extended class ( FileIO) just read the file txt and return the integer or string ( from the txt file)
    I already did a main method to that class and tested it, it works fine.
    So now the problem is to print the integer ( that the extended class gets from the txt. ) inside the Super class. I mean , is the same thing but now im testing the Super class , just have to do the same thing, a super class method calls the extended class method and receive the integer from the txt file.
    i think the problem is when i create the instance of the FileIO object , maybe its constructor ...i don't know.
    The name of the txt file is passed from the super class to the extended class, but i think the error is not from there.
    this.aero_le = new BufferedReader(new FileReader(super.ficheiroleitura_aero()));  //  super calls ficheiroleitura_aero()  and receive the name of the txt file ( e.g "temp.txt")  so i think that is correct.
    here's the code of the Super class public class Aeroporto {
         private String filereader_voo = "temporary.txt";
         private String filereader_aero = "temp.txt";
         private String siglaAero = "";
         public FileIO file;
         public Aeroporto(){};
         public Aeroporto(String filereader_voo, String filereader_aero) throws IOException{
              this.filereader_voo = filereader_voo;
              this.filereader_aero =filereader_aero;     
              file = new FileIO();
         public String siglaAero() {
              return siglaAero; }
         public String filereader_aero(){
              return filereader_aero;
    public int nrLines() throws IOException{   // it was supose to retunr the number of lines ( integer) from the txt file .
              return Integer.parseInt(file.lerLinhaN(1,1));
    // main() {
    Aeroporto a = new Aeroporto();
              int v = a.nrLines();
              System.out.print(v);
    // ***********************************************************+
    // Extended Class
    public class FileIO extends Aeroporto{
         private String ficheiroescrita;
         private PrintWriter vooescreve, aeroescreve ;
         private BufferedReader voo_le, aero_read;
         public FileIO(){}
         public FileIO(String filereader_voo, String filereader_aero, String ficheiroescrita) throws IOException {
              super(filereader_voo, filereader_aero);
              this.ficheiroescrita = ficheiroescrita;
              //If file does not exists , create one.
              try{
                   this.aero_read = new BufferedReader(new FileReader(super.filereader_aero()));
                   aero_read.close();
              catch(IOException ex){
                   this.aeroescreve = new PrintWriter(new FileWriter(ficheiroescrita));
                   aeroescreve.close();
    public String lerLinhaN(int line, int column) throws IOException{  // this method works fine , i already tested this class.
              this.aero_read = new BufferedReader(new FileReader(super.filereader_aero()));
              for(int i = 0; i != line-1; ++i) aero_read.readLine();
              String linha = aero_read.readLine();
              String [] words = linha.split(" ");
              return words[column-1];
    Maybe the error is that i use to test the Super class a default contructor on both classes... i don't know where the error is, i also did two small classes ( super and another that extends ) and get the string "Hello" from the super and print it inside the extended..and it works, that's why i think the error is when i call the extended class .. need help.
    thanks.

    Ok,
    This one might actually work... atleast it compiles.import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.File;
    import java.io.PrintWriter;
    import java.io.FileWriter;
    import java.io.IOException;
    public abstract class FileIO {
         public static boolean CreateOutputFileIfNotExists(
              String outputFilename //the name of the file to ensure exists.
         ) throws IOException
              final String functionName = "FileIO.CreateOutputFileIfNotExists";
              boolean retVal = false;
              //If the output file does does not exist then create it.
              //post condition: output file exists or an IOException has been thrown.
              BufferedReader infile = null;
              try{
                   infile = new BufferedReader(new FileReader(outputFilename));
                   retVal = true;
              } catch(IOException ex) {
                   PrintWriter outfile = null;
                   try {
                        outfile = new PrintWriter(new FileWriter(outputFilename));
                        retVal = true;
                   } catch(IOException ex2){
                        throw new IOException(functionName + ": cannot create output file " + outputFilename, ex2);
                   } finally {
                        outfile.close();
                        if (outfile.checkError()) {
                             throw new IOException(functionName + ": error on output stream " + outputFilename);
              } finally {
                   try {
                        infile.close();
                   } catch(IOException ex){
                        throw new IOException(functionName + ": cannot close output file " + outputFilename, ex);
              return(retVal);
         public static String readLine(
                   String  inputFilename //the name of the file to read.
              , int     lineNumber    //1 based number of the line to read from.
         ) throws IOException
              final String functionName = "FileIO.readLine";
              String outputLine = null;
              // reads the numbered "lineNumber" from "inputFilename".
              BufferedReader infile = null;
              try {
                   infile = new BufferedReader(new FileReader(new File(inputFilename)));
                   for(int i=1; i<lineNumber; ++i) infile.readLine();
                   outputLine = infile.readLine();
              } catch(IOException ex){
                   throw new IOException(functionName + ": cannot read input file " + inputFilename, ex);
              } finally {
                   try {
                        infile.close();
                   } catch(IOException ex){
                        throw new IOException(functionName + ": cannot close input file " + inputFilename, ex);
              return(outputLine);
         public static String readWord(
                   String inputFilename  //the name of the file to read.
              , int lineNumber        //1 based number of the line to read from.
              , int wordNumber        //0 based number of the word to read.
         ) throws IOException
              final String functionName = "FileIO.readWord";
              String outputWord = null;
              // reads the numbered space-seperated "wordNumber" from the numbered "lineNumber" of "inputFilename"
              try {
                   String[] words = FileIO.readLine(inputFilename, lineNumber).split(" ");
                   if (wordNumber>0 && wordNumber<words.length) outputWord = words[wordNumber-1];
              } catch(IOException ex){
                   throw new IOException(functionName + ": cannot read input file " + inputFilename, ex);
              return(outputWord);
    }Design notes... FileIO is a generic helper class... there is nothing specific to Airports, flights, or any other "domain" specific stuff in it... so it's re-usable... you can keep it and reuse it on other projects, or even share it with your friends.
    So... The airport class will just call the static methods on FileIO like this    ....
        int lineNumber=1;
        int wordNumber=1;
        String airportCode = FileIO.readWord(airportsFilename, lineNumber, wordNumber);
        ....How's that?
    corlettk: my now mandatory edit.

  • 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 .
    Thanks

    This 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");
    }

  • 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. :)

  • How to pass subclass to variable of super class ?

    class /EVUIT/EXCH_PRD_GUI definition
    public section.
      methods CONSTRUCTOR
        importing
          value(I_APPLICATION) type ref to /UIT/EXCH_PRD_APP optional
          value(I_REPID) like SY-REPID .
    class /UIT/EXCH_PRD_VERT_NN_MODEL definition
      public
      inheriting from /EVUIT/EXCH_PRD_APP
      create public .
    DATA: l_vert_nn_model type ref to /uit/exch_prd_vert_nn_model.
    DATA: l_gui type ref to /uit/exch_prd_gui_vbeleg.
       CREATE OBJECT l_vert_nn_model
            EXPORTING
              I_ALV_RECORDS = gt_alv_records[].
    CREATE OBJECT l_gui
       EXPORTING
         I_APPLICATION = l_vert_nn_model
         I_REPID = sy-repid .{color}
    Problem i am facing is for l_gui the parameter i_application is of type super class of l_vert_nn_model.
    Any suggestions, how can i pass this subclass object to the parameter which is of type super class?

    Hello Trivenn
    On SAP basis release 7.00 the following coding works:
    *& Report  ZUS_OO_DUMMY
    REPORT  zus_oo_dummy.
    *       CLASS lcl_local DEFINITION
    CLASS lcl_local DEFINITION.
      PUBLIC SECTION.
        METHODS:
          constructor
            IMPORTING
              value(io_instance)  TYPE REF TO zcl_edi_uk_svcs_out. " super class
      PRIVATE SECTION.
        data: mo_instance         type ref to object.
    ENDCLASS.                    "lcl_local DEFINITION
    *       CLASS lcl_local IMPLEMENTATION
    CLASS lcl_local IMPLEMENTATION.
      METHOD constructor.
        mo_instance ?= io_instance.
      ENDMETHOD.                    "constructor
    ENDCLASS.                    "lcl_local IMPLEMENTATION
    DATA: go_super    TYPE REF TO zcl_edi_uk_svcs_out,
          go_sub      TYPE REF TO zcl_edi_uk_svcs_out_customer,
          go_local    type ref to lcl_local.
    START-OF-SELECTION.
      CREATE OBJECT go_super.
      CREATE OBJECT go_sub.
      create object go_local
        exporting
          io_instance = go_sub.
      BREAK-POINT.
    END-OF-SELECTION.
    Regards
      Uwe

  • 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);
    }

  • How to access class variables in anonymous class??.

    I have a boolean class level variable. Fom a button action , this boolean will set to true and then it used in anonymous class. In anonymous class, I am getting default value instead of true. Could u anyone help in this plzzz.

    first of all, you don't want parent because that is something that Containers use to remember their containment hierarchy. you are thinking of super which is also incorrect, because that has to do with inheritance.
    the problem here is a scoping problem. you generally would use final if you were accessing variables in an anonymous class that are in the local scope. in this case, you just need to create some test code and play with it. snip the code below and play with it. it shows both the given examples and some additional ways to change/display class variables.
    good luck, hackerx
    import javax.swing.*;
    import java.awt.event.*;
    public class Foo extends JPanel
         private boolean the_b = true;
         public static void main(String[] args)
              Foo f = new Foo();
              JFrame frame = new JFrame();
              frame.getContentPane().add(f);
              frame.pack();
              frame.show();
         public Foo()
              // get your button
              JButton b = new JButton("Not!");
              b.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent ae)
                        // *** uncomment these to play around ***
                        // Foo.this.the_b = false; // this will work, but unnecessary
                        // the_b = false; // this works fine too
                        notFoo();
              this.add(b);
              // something to show the value that accesses a class variable
              // using an inner class instead of final nonsense
              DisplayThread t = new DisplayThread();
              t.start();
         private void notFoo()
              the_b = !the_b;
         class DisplayThread extends Thread
              public void run()
                   while(true)
                        System.err.println("boolean value: " + the_b);
                        try {
                        sleep(1000);
                        } catch(InterruptedException ie) {}
    }

  • Javah problem - super class could not be found !!

    Hi all,
    i have already posted this message but i didn't get enough help to solve my poor situation.
    and this is my problem:
    i got in my project (myProject) MyClass class.
    i wrote in another java class ,in OtherClass.class ,jni function that use MyClass object as parameter to the jni interface, as follow:
    private native int myFunction (MyClass obj); //function in OtherClass
    when i write the javah command line :
    javah -jni OtherClass (in order to create OtherClass.h)
    i always get the following error:
    A required super class myPackage.MyClass could not be found.
    my qoustion is how can i let the javah command line to know about the existence of myPackage.MyClass and how can i create and .h file when i using other class instance as jni function parameter in other class??
    Thanks Sendy.

    Lets define a few terms here.
    Java can be a java virtual machine which is what runs when you type 'java' on the command line. It is also represented by the compiler which runs when you type 'javac'. And in your case it also is represented by 'javah'.
    The class path defines where java finds classes that it needs.
    In older versions of java you had to tell it where to find everything. It couldn't even find java.lang.String unless you told it were it was. Now days you have to tell it where to find stuff that you add (or where 3rd party libraries are.)
    There are two ways to define the class path: a command line option and an environment variable.
    A class path can, currently, have three types of things in it:
    -A path to a zip file
    -A path to a jar file
    -A path
    For example
    -Path to zip file in windows: C:\mystuff\mylib\mystuff.zip
    -Path to zip file in unix: /opt/system/projects/mystuff/mystuff.zip
    -Path to jar file in windows: C:\mystuff\mylib\myjar.jar
    -Path to jar file in unix: /opt/system/projects/mystuff/myjar.jar
    -Path in windows: C:\mystuff\mylib
    -Path in unix: /opt/system/projects/mystuff
    Zip files aren't used as much anymore, but you should at least be aware of them.
    Java uses the class path to look for classes which are stored in files. It does this by translating the class name into a file name. It uses packages as directory names and class names as file names. So in your case it would try to find a class called myPackage.MyClass in a file called myPackage\MyClass.class. It would try to find that in any zip files, jar files, in in any paths that you specified in the class path.
    So java is trying to find myPackage\MyClass.class in your class path. It would try to find that in any zip files, jar files, in in any paths that you specified in the class path.
    Right now your class path is probably just "." which means that if you do the following commands
    cd C:\mystuff
    javah -jni OtherClass
    Then java is going to try to find myPackage.MyClass in the following file
    .\myPackage\MyClass.class
    That, because you 'cd' to C:\mystuff, translates to the following absolute path
    C:\mystuff\myPackage\MyClass.class
    So if java doesn't find that file then it is going to tell you that it can't find the file.
    So where is your file? Let's say it is here.
    C:\work\lib\myPackage\MyClass.class
    So you must tell javah where the root is. Keep in mind that 'myPackage' must be part of the path. That is not optional. The root is the directory above 'myPackage'. So the root is
    C:\work\lib
    So now you have a path that is ready for your class path. So your javah command could look like this
    javah -classpath ".;C:\work\lib" -jni OtherClass
    Or using an environment variable
    set CLASSPATH=.;C:\work\lib
    javah -jni OtherClass
    Keep in mind in the above that class path is a generic term and there can be other ways to define it. For example the Sun command "java" allows you to use "-classpath" or "-cp".
    So does the above help?

  • Super class code error..

    This is almost giving me an headache LOLOL gosh..
    //Super class
    public class X {
         private String pp = "xpto";
         public Y refy;
         public X(){}
         public X(String pp){
              this.pp = pp;
              refy = new Y();
         public String getPP(){ return pp; }
         public int p() {
              return Integer.parseInt(refy.testarString());
         public static void main(String[] xxx ){
              X x = new X();
              System.out.print(x.p());
    // Extended class
    public class Y extends X{
         private String ficheiro;
         public  Y() {}
         public Y(String pp, String ficheiro){
              super(pp);
              this.ficheiro = ficheiro;
         public String testarString() {
              String k = "2";
              return k;
    I can't print that "2" inside the main method of the Super class, does anyone could tell me why ?
    Message was edited by:
    Java__Estudante

    It would be helpful in the future if you could post the error you're getting (I'm assuming a NullPointerException)
    Take a look at your two contructors:
    > public X(){}
         public X(String pp){
              this.pp = pp;
              refy = new Y();
         }And then when you instantiate x, which one you call:
    >           X x = new X();
              System.out.print(x.p());See what I'm getting at? Also, using a member variable in your superclass that is an instance of the subclass is a little strange--what is that trying to accomplish?

  • Inherited methods of super class not shown in outline

    Hello, is there a possibility to display the methods and variables from the super class in the outline of the inheriting class in AiE?

    Hi Christian,
    We had discussed this, when we implemented the outline and quick outline some years, ago. Finally, we sticked to the approach that is used by other plug-ins in Eclipse (like JDT).
    There Outline View shows only the content of the current editor. This helps to keep the content of the view stable when you select an element for navigation (because you won't be able to switch the editor by selecting an element ).
    Inherited members are usually part of other editors, unless you have redefined a method in your current class. Therefore, they are not shown in Outline View (unless they are redefinitions).
    The filters like "Hide Non-Public Members of classes" can only hide elements of the current editor.
    Inherited members can be shown in the Quick Outline, because the interaction pattern is different there: If you navigate to an element the pop-up is closed. Therefore, a content change of the Quick-Outline does not hurt.
    Michael

  • Is it save to use class variables in a stateful application module?

    I've a simple question of understanding: Can I savely use class-variables in stateful application modules?
    Consider the following example:
    public class myStateFullAppModuleImpl extends ApplicationModuleImpl
    private int myVar=0;
    public int doMyWork()
    myVar++;
    return myVar;
    Is it save to use "myVar" this way considering AM-pooling? Or should I save "myVar" in the session instead?
    Thanks

    Remainder of code:
                for (int i=0; i < length; i++)
                   org.w3c.dom.Node child = nl.item(i);
                   if (child != null && "jbo.counter".equals(child.getNodeName()))
                      getSession().getUserData().put(
                         "jbo.counter", child.getFirstChild().getNodeValue());
                      int counterInt = getCounterValue();
                      counterInt++;
                      getSession().getUserData().put(
                         "jbo.counter", String.valueOf(counterInt));
                      break;
          public void prepareSession(oracle.jbo.Session session)
             super.prepareSession(session);
             try
                int counterInt = getCounterValue();
                counterInt++;
                getSession().getUserData().put("jbo.counter", String.valueOf(counter
    Int));
             catch (Exception e)
                e.printStackTrace();
          public int getCounterValue()
             int counterInt = 0;
             try
                String counter = (String)getSession().getUserData().get("jbo.counter[i][pre]Long postings are being truncated to ~1 kB at this time.

  • Instantiation of similar object over a super class deciding the sub class

    Hello all
    First, sorry if I'm duplicating an already answered question. I didn't searched very deep.
    Initial position:
    I have 2 Object (A1 and A2) which share the most (about 90%) of their instance variables an the associated methods. The values of the instance variables are retrieved in the real implementation from a stream. Depending of the data of the stream, I have to instantiate either a A1 or A2 object.
    A test implementation (using an int in case of the stream):
    The super class A:
    package aaa;
    public class A
      protected int version = -1;
      protected String name = null;
      protected AE ae = null;
      protected A()
      protected A(int v)
        // Pseudo code
        if (v > 7)
          return;
        if (v % 2 == 1)
          this.version = 1;
        else
          this.version = 2;
      public final int getVersion()
        return this.version;
      public final String getName()
        return this.name;
      public final AE getAE()
        return this.ae;
    }The first sub class A1:
    package aaa;
    public final class A1 extends A
      protected A1(int v)
        this.version = v;
        this.name = "A" + v;
        this.ae = new AE(v);
    }The second subclass A2:
    package aaa;
    import java.util.Date;
    public final class A2 extends A
      private long time = -1;
      protected A2(int v)
        this.version = v;
        this.name = "A" + v;
        this.time = new Date().getTime();
        this.ae = new AE(v);
      public final long getTime()
        return this.time;
    }Another class AE:
    package aaa;
    public class AE
      protected int type = -1;
      protected AE(int v)
        // Pseudo code
        if (v % 2 == 1)
          this.type = 0;
        else
          this.type = 3;
      public final int getType()
        return this.type;
    }To get a specific object, I use this class:
    package aaa;
    public final class AFactory
      public AFactory()
      public final Object createA(int p)
        A a = new A(p);
        int v = a.getVersion();
        switch (v)
        case 1:
          return new A1(v);
        case 2:
          return new A2(v);
        default:
          return null;
    }And at least, a class using this objects:
    import aaa.*;
    public final class R
      public static void main(String[] args)
        AFactory f = new AFactory();
        Object o = null;
        for (int i = 0; i < 10; i++)
          System.out.println("===== Current Number is " + i + " =====");
          o = f.createA(i);
          if (o instanceof aaa.A)
            A a = (A) o;
            System.out.println("Class   : " + a.getClass().getName());
            System.out.println("Version : " + a.getVersion());
            System.out.println("Name    : " + a.getName());
            System.out.println("AE-Type : " + a.getAE().getType());
          if (o instanceof aaa.A2)
            A2 a = (A2) o;
            System.out.println("Time    : " + a.getTime());
          System.out.println();
    Questions:
    What would be a better way to encapsulate the logic into their respective objects ? Is there a way to let the super class A itself identify the type of the object and then extend from A to either A1 or A2 ?
    Thanks in advance
    Andreas

    Hello jduprez
    First, I would thank you very much for taking the time reviewing my problem.
    Just for the record: have you considered regular serialization? If you control the software at both ends of the stream, you could rely on standard serialization mechanism to marshall the objects and unmarshall them automatically.In my case, I can't control the other site of the stream. At the end, the data comes from a FileInputStream and there aren't objects on the other site, only pur binary data.
    - It seems you have one such factory class. Then you already have encapsulated the "determine class" logic, you don't need to add such logic in superclass A.I thought from an OO view, that the super class A is responsible of doing that, but that's where the problem starts. So at the end, it's better doing it in the factory class.
    - A itself encapsulates the logic to load its own values from the stream.
    - A1 and A2 can encapsulate the logic to load their own specific value from a stream (after the superclass' code has loaded the superclass' attributes values).
    My advise would be along the lines of:
    public class A {
    .... // member variables
    public void load(InputStream is) {
    ... // assign values to A's member variables
    // from what is read from the stream.
    public class A1 extends A {
    ... // A1-specific member variables
    public void load(InputStream is) {
    super.load(is);
    // now read A1-specific values
    public class AFactory {
    public A createA(InputStream is) {
    A instance;
    switch (is.readFirstByte()) {
    case A1_ID:
    a = new A1();
    break;
    case A2_ID:
    a = new A2();
    break;
    a.load(is);
    }The example above assumes you have control over the layout of the data in the stream (here for a given A instance, the attributes defined in A are read first, then come the subclass-specific attributes.
    The outcome is: you don't have to create a new A( ) to later create another instance, of a subclass.I like the idea. In the AFactory, is the "A instance;" read as "A a;" ?
    Is there a way to let the super class A itself identify the type of the object and then extend from A to either A1 or A2 ?Note I initially read this question as "can an instance of a class mutate into another class", to which the answer is no (an object has one single, immutable class; it is an instance of this class, and of any superclass and superinterface, but won't change its class at runtime).Yes, I have been thinking about a way for mutating into a subclass to keep the already initialized values from the A class without copying or parsing again. But preventing an instance of an A class will be my way. So, in this aspect, Java didn't changed in the last 10 years... It's a long time ago I've used Java for some real projects.
    You can, however, create an instance of another class, that copies the values off a priori A instance. Your example code was one way, another way could be to have a "copy constructor":
    public class A {
    public A(A model) {
    this.att1 = model.att1;
    this.att2 = model.att2;
    public class A1 {
    public A1(A model) {
    super(model);
    ... // do whatever A1-specific business
    )Still, I prefer my former solution less disturbing: I find the temporary A instance redundant and awkward.Nice to know. I prefer the first solution too.
    Thank you again for the help and advices. My mind is searching sometimes for strange solutions, where the real is so close ;-)
    Andreas

  • Is CLASS VARIABLE changed?

    I have two classes in same package. I defined a class variable 'no_of_gear' and later changed its value. The changed value
    works in the same class but does not work in sub-class in same package.
    class ClassVar {
         static int no_of_gear = 5;
         public static void main(String[] args) {
              System.out.println(no_of_gear); //Prints 5
              ClassVar cv = new ClassVar();
              System.out.println(cv.no_of_gear); //Prints 5
              cv.no_of_gear = 8;
              System.out.println(cv.no_of_gear); //Prints 8
              System.out.println(no_of_gear); //Prints 8
    }Here is sub-class in same package.
    class ClassVarAcc extends ClassVar {
         public static void main(String[] args) {
              System.out.println(no_of_gear); //Prints 5
              ClassVar cv = new ClassVar();
              System.out.println(cv.no_of_gear); //Prints 5
    }Java Tutorial by SUN reveals that if class variable is changed by one object it is changed for all objects of that class. But, my code does not support the statement. Please, Can you clarify it?

    Yes i do but not to the extent you are pointingto.
    Why can't you just say you don't when you don't?
    Can you answer in details?Look at your super class
    class ClassVar {
    static int no_of_gear = 5;
    public static void main(String[] args) {
         System.out.println(no_of_gear); //Prints 5
         ClassVar cv = new ClassVar();
              System.out.println(cv.no_of_gear); //Prints 5
         cv.no_of_gear = 8;
              System.out.println(cv.no_of_gear); //Prints 8
         System.out.println(no_of_gear); //Prints 8
    }In what method does the value of no_of_gear change?
    Now look at the sub-class. Do you see yourself
    calling this method?OH my dear. It is class variable that can be accessed directly (unlike instance variables) without the need of some method to change its value.
    Here i change it. (Remeber: a copy of instance variable is passed to an instance of some class but no copy of class variable is passed to an instance of that class)
         cv.no_of_gear = 8;
         System.out.println(cv.no_of_gear); //Prints 8
    Here it works fine.
         System.out.println(no_of_gear); //Prints 8
    But, why does not it work in sub-class?

  • 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....

Maybe you are looking for

  • Problems with new iPOD shuffle

    Just got a new iPOD shuffle, and can't get it to work. i followed all the troubleshooting directions (worked on it for about 2 hours, twice)with the same problems. Updated the software version, restored the settings, no help. I copied all my CD with

  • 802.11n enabler issue

    Hi, 1st time MAc user after 15 years of PC. So forgive me for any terminology screw ups. Got a Mac Book Pro, 2.33 Ghz Duo 2 Core. So I tried downloading the enabler and it give me the incorrect hardware error message. I guess how do I double check th

  • Bookmarks keep appearing in autocomplete

    I have tried going to "Tools -> Options -> Privacy -> When using the location bar, suggest: " If this option is set to "History and bookmarks" bookmarks will show up as the first suggestion with a star next to them. If this option is set to "History"

  • HT5654 your update erased all my itunes files!

    1-29-14 update erased 10 years worth of itunes music and audio files.  How do I get them back? I have a HP Windows 7 computer.

  • Connection Settings between Content Server and DMS server

    Dears, I installed DMS server and Content Server,Now I need to do connection settings between these server. Both are installed on seprate servers. So please suggest what are the steps to set connection between these servers. Shivam