I know super() is used to retrieve the instance variables from parent class, but when I saw the codes as follow:
public class novel extends literature {
private String title;
private String writer;
public novel(String title)
{
super("novel");
this.title = title;
this.writer = "Unknow";
}
public novel(String title, String writer)
{
super("novel");
this.title = title;
this.writer = writer;
}
public String getInfo()
{
return getGenre() + "\nTitle: " + title + "\nWriter: " + writer;
}
public static void main(String[] args)
{
novel n = new novel("The devil wears prada", "Lauren Weisberger");
System.out.println(n.getInfo());
}
}
When I saw this: super("novel"); I get very confuse, how come the child class name can be put in the super method?
And I don't know why this.writer = "unknown";
is here for what? Why don't it just set it to be writer?
Sorry for throwing so many questions to you guys, but will appreciate a lot for any solutions.
I'm sorry guys i still did not totally get why it used super("novel")? If we say novel here is a string, but then why we use that string which has the same name as "novel class"?
super ("novel")
means that you pass a String as argument for the constructor of the parent class.
this.writer = "Unknow"
means that you pass the String value "Unknow"
to a member of the current class instance. You could also pass eg. "Mark Twain", the writer's variable value will then be "Mark Twain".
For more information http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
//Parentclass
public class Book {
private String genre;
private String isbn;
//As you can see we have two constructors.
//The first with only one argument
public Book (String genre)
this.genre = genre;
}
//The second one with two arguments
public Book (String genre, String isbn) {
this.genre = genre;
this.isbn = isbn;
}
}
//subclass
class Novel extends Book{
public Novel(String isbn)
super("novel", isbn);
//super() has now two arguments, because we are calling the second constructor
//which has two args.
//Now, in the parent class members genre = "novel" and isbn equals the value passed in the
//child constructor.
//This is the same as using the parent constructor inner body in this constructor.
//Normally the parent constructor gets overwritten on inheritance.
//But super makes its possible to use the parent constructor.
}
For more examples check this super() documentation