So I'm writing some code that involves extending a class I have previously written in which files are created and named using a constructor that takes in a name and a size of type long. In that original class, I verified within the constructor that the entered file name contained one "." character but did not require a specific extension on the file. For this new class that I am writing, I am requiring the name's extension be ".mp3".However, my compiler does not like verification before the super constructor.
This is my current code:
public class Song extends DigitalMedia{
private String artist;
private String album;
private String name;
private long size;
public Song(String aName, long aSize, String aArtist, String aAlbum){
super(aName, aSize);
setArtist(aArtist);
setAlbum(aAlbum);
}
Is there any way to verify that "aName" contains ".mp3" before I create that constructor?
However, using super() is not compulsory. Even if super() is not used in the subclass constructor, the compiler implicitly calls the default constructor of the superclass.
this or super Must Be the First Statement in the Constructor. Whenever we call a constructor, it must call the constructor of its base class. In addition, you can call another constructor within the class. Java enforces this rule by making the first call in a constructor be to this or super.
“this()” is used to call the constructor of the current class and “super()” is used to call the constructor of the immediate parent class.
If we call "super()" without any superclass Actually, nothing will be displayed. Since the class named Object is the superclass of all classes in Java. If you call "super()" without any superclass, Internally, the default constructor of the Object class will be invoked (which displays nothing).
I can't say whether it's the best way to design your program, but you could call a validator method inside one of the super
arguments:
public Song(String aName, long aSize, String aArtist, String aAlbum){
super(validateName(aName), aSize);
setArtist(aArtist);
setAlbum(aAlbum);
}
private static String validateName(String name) {
if (whatever) {
throw new Whatever();
}
return name;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With