1 2 Previous Next 17 Replies Latest reply: Oct 21, 2006 10:35 PM by 800308 RSS

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

    807598
      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.
        • 1. Re: Weird one..  need a little help  thnks
          807598
          Lets forget the code above ...help me on this one , im getting the same error. something is missing me, and i don't know what it is.
          //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
          • 2. Re: Weird one..  need a little help  thnks
            800308
            I can't see the problem... so I'm playing with the code... I'll get back to you. Keith.
            • 3. Re: Weird one..  need a little help  thnks
              807598
              Exception in thread "main" java.lang.NullPointerException
                   at X.p(X.java:18)
                   at X.main(X.java:26)

              thanks :S o/
              • 4. Re: Weird one..  i can't return a variable from the extended to the super c
                800308
                Yep, this is all very wierd... it's not normal for super and sub-types to contain references to each other... coz you loose the flexibility gained by polymorphism.

                The short answer is, the no-arg super constructor (X(){} ) doesn't instantiate the subclass Y.

                I took the liberty of changing names to something meaningful.

                Super class
                //Super class
                public class XSuperclass {
                
                     private String pp = "xpto";
                     public XSubclass subclass;
                
                     public XSuperclass() {
                          subclass = new XSubclass();
                     }
                
                     public XSuperclass(String pp) {
                          this.pp = pp;
                          subclass = new XSubclass();
                     }
                
                     public String getPP(){ 
                          return pp; 
                     }
                
                     public int getK() {
                          System.out.println("subclass.getK()=" + subclass.getK());
                          return Integer.parseInt(subclass.getK());
                     }
                
                     public static void main(String[] args) {
                          XSuperclass superclass = new XSuperclass();
                          System.out.println(superclass.getK());
                     }
                }
                Sub Class
                // Extending class
                public class XSubclass extends XSuperclass{
                     
                     private String string;
                     
                     public XSubclass() {
                     }
                     
                     public XSubclass(String pp, String string){
                          super(pp);
                          this.string = string;
                     }
                     
                     public String getK() {
                          String k = "2";
                          return k;
                     }
                }
                but when you add it it you get a Stack overflow
                ---------- run ----------
                Exception in thread "main" java.lang.StackOverflowError
                     at XSubclass.<init>(XSubclass.java:6)
                     at XSuperclass.<init>(XSuperclass.java:8)
                     at XSubclass.<init>(XSubclass.java:6)
                     at XSuperclass.<init>(XSuperclass.java:8)
                     at XSubclass.<init>(XSubclass.java:6)
                     at XSuperclass.<init>(XSuperclass.java:8)
                     at XSubclass.<init>(XSubclass.java:6)
                     at XSuperclass.<init>(XSuperclass.java:8)
                     .... about 5000 of these ....
                
                Output completed (12 sec consumed) - Normal Termination
                because there's a cirular reference. new Super creates a new Subclass which calls super(pp) in it's constructor, which creates a new Subclass... and so on adfinitum.

                This is definately bad code.

                What are you trying to do anyway?

                Keith.

                Keith.

                corlettk: sloppy fingers.
                • 5. Re: Weird one..  need a little help  thnks
                  807598
                  oh my god LOL ...gosh

                  the main problem is in the first post.

                  I've a extended class FileIO that reads from the txt file the number of lines. and keep that string ( with the number e.g 28 ) inside the method lerLinhaN and returns....then i want to catch that string with the nrLines() of the super class , cast the string to integer and print on the main method, just to make sure that the nrLines() is returning the number of lines of the txt file. that's all.

                  Message was edited by:
                  Java__Estudante
                  • 6. Re: Weird one..  i can't return a variable from the extended to the super c
                    800308
                    Aha, I don't speaken ze dutsche, but I reckon there isn't really an "is-a relationship" between these two classes.

                    Aeroporto looks like "data class" gone a bit wrong.

                    FileIO looks like "utilities class" ... and would better be written as an abstract (non-instantiable helper class) with static methods to do all the fileIO.

                    Do you agree?

                    Keith.
                    • 7. Re: Weird one..  i can't return a variable from the extended to the super c
                      807598
                      my english is bad LOLOLO

                      Aeroporto means Airport lol

                      FileIO just reads from the txt file ...and the airport class just catch what the fileIo catches =P


                      Oh I got it , like copy pasted all the methods from the airport class to the FileIO class ? is that it ? and do all the things inside the FileIO ?

                      Is that what u said ?

                      Message was edited by:
                      Java__Estudante
                      • 8. Re: Weird one..  i can't return a variable from the extended to the super c
                        800308
                        OK, so you're english isn't too great, but it's a lot better than my espanole.

                        So this is gonna be a bit of challenge. I do like challenge.

                        Could you translate the code in your original post into english?... just do your best, and if you can't think of "the right word" just do your best to describe "the thing" in a comment.

                        I'll try the same.

                        Keith.

                        corlettk: fuddle fingers again.
                        • 9. Re: Weird one..  i can't return a variable from the extended to the super c
                          807598
                          Aha, I don't speaken ze dutsche, but I reckon there
                          isn't really an "is-a relationship" between these two
                          classes.
                          Seconded. (Forgive me if this is overly pedantic, but he means FileIO probably shouldn't extend Aeorporto, but Aeroporto should instead have a FileIO)
                          • 10. Re: Weird one..  i can't return a variable from the extended to the super c
                            807598
                            oh sure i can :)

                            but read the post before yours :)

                            i goona translate lol and its portuguese not spanish LOL
                            • 11. Re: Weird one..  i can't return a variable from the extended to the super c
                              800308
                              kindofblue can translate... I've been surrounded by IT pro's for the last 10 years, and you kind of forget that normal poeple don't speak the same language. Keith.
                              • 12. Re: Weird one..  i can't return a variable from the extended to the super class
                                807598
                                public class Airport {
                                     private String filereader_flight = "temporary.txt"; // this will be another txt file , this one for the flights
                                     private String filereader_aero = "temp.txt";    //aero = air = airport =P
                                     
                                          
                                     private String siglaAero = "";    // siglaAero =  sigla means a small group of chars  like e.g  Barcelona ->  BA  
                                     public FileIO file;
                                     
                                     
                                     
                                     public Airport(){};
                                     
                                     public Airport(String filereader_flight, String filereader_aero) throws IOException{
                                          this.filereader_flight = filereader_flight;
                                          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)); // lerLinhaN  it the method of the extended class means  read (n) line from the txt file
                                          
                                     }
                                // main() {
                                 
                                Aeroporto a = new Aeroporto();
                                          int v = a.nrLines();
                                          System.out.print(v);
                                          
                                          
                                     }
                                 
                                // ***********************************************************+
                                 
                                // Extended Class 
                                 
                                 
                                public class FileIO extends Aeroporto{
                                     
                                     private String ficheiroescrita;   // String filewrite
                                     private PrintWriter vooescreve, aeroescreve ;
                                     private BufferedReader voo_le, aero_read;     // voo_le = flight_read 
                                     
                                     public FileIO(){}
                                     
                                     public FileIO(String filereader_flight, String filereader_aero, String ficheiroescrita) throws IOException {  // ficheiroescrita = filewrite
                                          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();  // linha = line
                                          String [] words = linha.split(" ");
                                                                   
                                          return words[column-1];
                                                    
                                     }
                                Message was edited by:
                                Java__Estudante
                                • 13. Re: Weird one..  i can't return a variable from the extended to the super c
                                  800308
                                  Sorry I took a while... got side-tracked by a search for wheat free, glutten free beer :-)
                                       public static CreateOutputFileIfNotExists(String outputFilename) 
                                       throws IOException 
                                       {
                                  
                                            static final String functionName = "FileIO.CreateOutputFileIfNotExists";
                                  
                                            //If the output file does does not exist then create it.
                                            //post assert: output file exists or an IOException has been thrown.
                                            BufferedReader infile = null;
                                  
                                            try{
                                  
                                                 infile = new BufferedReader(new FileReader(outputFilename));
                                  
                                            } catch(IOException ex) {
                                  
                                                 PrintWriter outfile = null;
                                                 try {
                                                      outfile outfile = new PrintWriter(new FileWriter(outputFilename));
                                                 } catch(IOException ex){
                                                      throw new IOException(functionName + ": cannot create output file " + outputFilename, ex);
                                                 } finally {
                                                      try { 
                                                           outfile.close();
                                                      } catch(IOException ex){
                                                           throw new IOException(functionName + ": cannot close input file " + outputFilename, ex);
                                                      }
                                                 }
                                  
                                            } finally {
                                  
                                                 try { 
                                                      infile.close();
                                                 } catch(IOException ex){
                                                      throw new IOException(functionName + ": cannot close output file " + outputFilename, ex);
                                                 }
                                  
                                            }
                                       }
                                  
                                  
                                       public static String readWord(String inputFilename, int line, int word) 
                                       throws IOException 
                                       {
                                            static final String = functionName = "FileIO.readWord";
                                            // reads the numbered space-seperated "word" from the numbered "line" of "inputFilename"
                                            try {
                                                 this.infile = new BufferedReader(new FileReader(new File(inputFilename)));
                                                 for(int i=0; i<line; ++i) infile.readLine();
                                                 String line = infile.readLine();
                                                 String [] words = line.split(" ");
                                                 return words[word-1];
                                            } catch(IOException ex){
                                                      throw new IOException(functionName + ": cannot read input file " + inputFilename, ex);
                                            } finally 
                                            infile.close
                                  
                                       }
                                  
                                  }
                                  • 14. Re: Weird one..  i can't return a variable from the extended to the super c
                                    800308
                                    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.
                                    1 2 Previous Next