Instantiation from within Methods
Hi, I'm a novice. I want to understand why this code will not work. This is an exercise in implementing interfaces, and I've missed something fundamental. If I invoke a method (say charAt) from another class, it fails with nullpointer exception, because mySeg cannot be instantiated from within the constructor (in my code). The only way I've tried that works is instantiating mySeg within every method. e.g Segment mySeg = new Segment(jarray,0,jlen); at the start of the method. Surely, the object mySeg will exist after the constructor when the class is instantiated with:-
char[] testArray = {'\u0054','\u0048','\u0049','\u0053'};
CharSeqPlus myCS = new CharSeqPlus(testArray,4);
The problem class is:-
Code java:
public class CharSeqPlus implements CharSequence{
char[] jarray;
int jlen;
Segment mySeg;
/* Constructor */
public CharSeqPlus(char[] arrayIn, int lenIn) {
jarray = arrayIn;
jlen = lenIn;
Segment mySeg = new Segment(jarray,0,jlen);
/* in the other methods, mySeg is not instatiated after */
/* this statement, so do a new one in each method! */
}
public char charAt(int locIn){
Segment mySeg = new Segment(jarray,0,jlen);
return mySeg.charAt(locIn);
}
public int length(){
Segment mySeg = new Segment(jarray,0,jlen);
return mySeg.length();
}
public CharSequence subSequence(int stIn, int enIn){
Segment mySeg = new Segment(jarray,0,jlen);
return mySeg.subSequence(stIn,enIn);
}
public String toString(){
Segment mySeg = new Segment(jarray,0,jlen);
return mySeg.toString();
}
public String reversed(){
Segment mySeg = new Segment(jarray,0,jlen);
String revString = "";
for(int i=jlen-1;i>=0;i--) {
revString = revString + jarray[i];
}
return revString;
}
} //class
Thanks for your help. It must be very fundamental!
Re: Instantiation from within Methods
All variables have a certain scope. If a variable is created within a certain block of code, its scope ends when that block ends. For instance
Code :
for ( int i = 0; i < 10; i++ ){
int j = i;//
}
System.out.println(j);//j is out of scope
There are times when the scope is defined at compile time (the above example - which won't compile) versus runtime (your example). The easy solution for you is to not create the local variable inside the constructor, but use the instance variable (named the same) that is defined in your class
Re: Instantiation from within Methods
Great, thanks very much! I instantiated class field mySeg outside of the class, after instantiating the new class like this:- and deleted the superfluous instantiations:-
CharSeqPlus myCS = new CharSeqPlus();
myCS.mySeg = new Segment(testArray,0,4); // instantiates mySeg (once only)
Learned something new.