【问题标题】:Difference between creating an object of subclass in SuperClass Vs Subclass在 SuperClass Vs Subclass 中创建子类对象的区别
【发布时间】:2018-10-13 09:09:26
【问题描述】:

在子类和超类中创建子类的对象有什么区别?

我的超类是 -> LibraryItem.Java

我的子类是 -> Book.java

1和2有什么区别

         1. LibraryItem book_01 = new Book() //In superclass
         2. book_01 = new Book() //In subclass

注意:- 请注意我删除了一些 get、set 和一些抽象方法。这里只添加了重要的部分

 public abstract class LibraryItem {  
    private boolean status;
    private String borrowedDateTime;
    private Reader reader;
    private int isbn;
    private String title;
    private String publicationDate;
    private String sector;

    public abstract void getItemDetails();
    public abstract void returnItem();
    public abstract void readerDetails();
    public abstract void borrowItem();

    public static void main (String [] args){

    }

}


public class Book extends LibraryItem {
public String author;
    public String publisher;
    public int no_Of_Pages;
    private int readerID;

    Book[] bookArray = new Book[100];

    Book(int isbn, String title, String sector, String publicationDate,
         boolean status, String borrowedDateTime, String author, String publisher, int no_Of_Pages, int readerId){
        super();
        this.setIsbn(isbn);
        this.setTitle(title);
        this.setSector(sector);
        this.setPublicationDate(publicationDate);
        this.setStatus(status);
        this.setBorrowedDateTime(borrowedDateTime);
        this.author = author;
        this.publisher = publisher;
        this.no_Of_Pages = no_Of_Pages;
        this.setReaderID(readerId);

    }





    //Create 100 Books

    public void createBooks(){
        Book book_01;
        book_01 = new Book(00001, "Harry Potter", "Adveture", "2012.12.12",
                true, "asd","J.K Rowling", "Disney", 500, 0);
        bookArray [0] = book_01;

    }

}

【问题讨论】:

  • 无论您在哪里创建类的实例,都应该没有区别。你到底想找到什么?
  • new Book(); 做同样的事情假设Book 是同一个类。你有什么疑问?
  • 我在子类中有一个数组“ bookList [] ”,我想将对象添加到数组中。我想知道,根据真正的 OOP 规则,我应该在哪里创建对象。此外,该对象具有超类的属性,超类是抽象类和子类的属性。
  • 您能否发布您的超类和子类的代码,并在您尝试在 bookList[] 数组中添加对象的位置显示您的代码?
  • 如果您可以发布minimal reproducible example,它会更容易为您提供帮助。你在哪里做的详细信息可能很重要。

标签: java oop object


【解决方案1】:

看起来有点奇怪,但是

在 JAVA 中:

非静态方法取决于运行时(运行时绑定类型)类型 对象而不是指向的引用。

在你的情况下, 时间 book_01 都指向堆中的 Book 类对象

使用超类引用的优点: 1.优点是可以将子类对象的任何地址给超类,如果我们不知道确切的对象类型,在运行时绑定的情况下很有用

2.Cons是使用超类对象引用子类对象,我们不能调用子类的方法和属性。

使用子类引用的优缺点:

1.优点是对象可以访问超类的属性和方法,也可以访问它。

2.Cons 是对象不能作为对其他类的引用,除非它们是该类的子类。

【讨论】:

    猜你喜欢
    • 2012-11-16
    • 1970-01-01
    • 2016-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多