Reputation: 137
So I have class called 'EducationalBook' that is subclass of class 'Book'. And class 'Book' is the subclass of class 'PaperPublication'.
In my understanding, copy constructor for normal class(like 'PaperPublication') can be written as follow:
public class PaperPublication
{
String title;
double price;
int nOP; //number of pages
public PaperPublication(PaperPublication p)
{
title = p.title;
price = p.price;
nOP = p.nOP;
}...
However, I am not sure how to build a copy constructor for a subclass with parameter of that class itself only(for example: 'Book' class with parameter (Book b) ONLY). The reason why I want only one parameter is because there's a rule that for copy constructor of subclass, I have to call parent class's copy constructor(I believe this means use "super()" right?). After some research, though I did not find a clear answer, I built as such:
public class Book extends PaperPublication
{
long ISBN;
int issued;
String author;
public Book(Book b)
{
super(b.getTitle(), b.getPrice(), b.getNOP());
ISBN = b.ISBN;
issued = b.issued;
author = b.author;
}...
I am not even sure this is correct way to do it, but it at least compiled without occurring any compile-stage error.
However, for EducationalBook class, I don't have any single idea to build a copy constructor. Since Java does not allow something like super.super(), and I am not allowed to utilize parametrized constructor, but only copy constructor of parent class.
public class EducationalBook extends Book
{
int edition;
String speciality;
public EducationalBook(EducationalBook e)
{
//??? no clue..
}
public EducationalBook() // default constructor. is this right?
{super();}
}
(And for additional question, is that default constructor right?)
I feel like my understanding of inheritance of Java is weak overall. Any enlightenment for me?
Upvotes: 2
Views: 8073
Reputation: 6038
It's easier than you think.
The copy constructor of Book
:
public Book(Book b)
{
super(b);
ISBN = b.ISBN;
issued = b.issued;
author = b.author;
}
And the copy constructor of EducationalBook
:
public EducationalBook(EducationalBook b)
{
super(b);
edition = b.edition;
speciality = b.speciality;
}
Upvotes: 6