gpt4 book ai didi

java - 我对 super() 的用法感到困惑

转载 作者:太空宇宙 更新时间:2023-11-04 06:33:11 24 4
gpt4 key购买 nike

我知道 super() 是用来从父类中检索实例变量的,但是当我看到代码如下时:

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());
}

}

当我看到这个时: super("novel");我很困惑,为什么子类名可以放在 super 方法中?我不知道为什么 this.writer = "unknown"; 在这里是为了什么?为什么不直接将其设置为作家?

很抱歉向你们提出了这么多问题,但非常感谢您提供任何解决方案。

对不起,大家我仍然不完全明白为什么它使用 super (“小说”)?如果我们说小说这里是一个字符串,那么为什么我们使用与“小说类”同名的字符串呢?

最佳答案

super ("novel") 表示您将 String 作为参数传递给父类的构造函数。

this.writer = "Unknow" 表示将字符串值 "Unknow" 传递给当前类实例的成员。你也可以通过例如。 “Mark Twain”,作者的变量值将是“Mark Twain”。

了解更多信息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.


}

更多示例check this super() documentation

关于java - 我对 super() 的用法感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25808094/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com