Overriding method to pass a different set of delimiters to Scanner
Few questions on over riding.
I am interiting a method openRead
from another class, the method is to be overridden so that the scanner class uses the provided delimiter pattern, which is referenced. I need to make use of the scanner class useDelmiter method
method from another class
public boolean openRead() throws FileNotFoundException
{
sc = new Scanner(new File(fileName));
开发者_开发技巧 if (fileName != null)
{
return true;
}
else
{
return false;
}
}
delimiter
protected final String DELIMITERS = "[\\s[^'a-zA-Z]]";
I'm at a loss to how i over ride this using the constant delimiter.
So you just want the overridden version to use a different delimiter pattern for the Scanner
? I suggest taking a look at the Scanner API as it documents how to use a different delimiter pattern.
public boolean openRead() throws FileNotFoundException
{
boolean result = super.openRead();
sc.useDelimiter(DELIMITERS);
return result;
}
edit
Or perhaps you just don't know what overriding is in Java, and for that you should read more in the Java tutorials.
But essentially, if you had some class:
public class ScannerUserParent
{
protected Scanner sc;
private String filename = null;
// all that other stuff like constructors...
public boolean openRead() throws FileNotFoundException
{
sc = new Scanner(new File(fileName));
if (fileName != null)
{
return true;
}
else
{
return false;
}
}
}
Then you subclass that class (or extends
):
public class ScannerUserChild extends ScannerUserParent
{
protected final String DELIMITERS = "[\\s[^'a-zA-Z]]";
// stuff like constructors...
public boolean openRead() throws FileNotFoundException
{
boolean result = super.openRead(); // we are calling the parent's openRead() method to set up the Scanner sc object
sc.useDelimiter(DELIMITERS);
return result;
}
}
However, there are other things that can prevent you from doing exactly this. For example, if the sc
member was private
scope, then the subclass could not use it directly in the manner I have shown.
In my example, sc
uses protected
access, so the class and its subclasses can use it.
In case there's a private
Scanner
, and assuming the parent has a getScanner()
method that returns you the Scanner
, you could do this:
public boolean openRead() throws FileNotFoundException
{
boolean result = super.openRead(); // we are calling the parent's openRead() method to set up the Scanner sc object
Scanner sc = getScanner();
sc.useDelimiter(DELIMITERS);
return result;
}
精彩评论