Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking the validity of a variable before calling the super constructor

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?

like image 420
J Zane Avatar asked Feb 11 '17 18:02

J Zane


People also ask

Is it necessary to call super () inside a 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.

Why must super () or this () Be the first statement in a constructor?

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.

How are this () and super () method used with constructor?

“this()” is used to call the constructor of the current class and “super()” is used to call the constructor of the immediate parent class.

What happens when you don't use super () constructor?

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


1 Answers

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;
}
like image 132
user2357112 supports Monica Avatar answered Oct 14 '22 22:10

user2357112 supports Monica