0

I have a class like so:

public abstract class Book {

    public abstract double retailPrice();

    private String title, author, ISBN;
    private double price;

    public Book() {
        title = "";
        author = "";
        ISBN = "";
        price = 0.00;
    }
    public Book(String title, String author, String ISBN, double price) {
        this.title = title;
        this.author = author;
        this.ISBN = ISBN;
        this.price = price;
    }
    public String getTitle() {
        return title;
}

With objects of a class Textbook (shown below) in an array:

public class Textbook extends Book {

    private String course;

    @Override
    public double retailPrice() {
        return super.getPrice() + (super.getPrice() * .10);
    }
    public Textbook() {
        course = "";
    }
    public Textbook(String course) {
        this.course = course;
    }
    public String getCourse() {
        return course;
    }
    public void setCourse(String course) {
        this.course = course;
    }
}

My array is full of objects such as:

Book[] books = new Book[100];
books[i] = new Textbook(courseName);

When I call my array as using books[i]. the only method available is getTitle() of Textbook's inherited class (Book).

So my question is, how do I get access to the getCourse() function of the Textbook class?

2 Answers 2

3

If all elements of your books array are going to be Textbook instances, you can declare the array to be of type Textbook books[] instead of Book[]. Otherwise, you'll need to cast and, to be safe, you'll need to test the book type:

String course = null;
if (books[i] instanceof Textbook) {
    course = ((Textbook) books[i]).getCourse();
}

A variation is to skip the instanceof test and instead wrap the code in a try/catch statement to catch any ClassCastException that might be thrown. Of course, if you know by some other logic that books[i] must be an instance of Textbook you can safely eschew both the type check and the try/catch block.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect. I do have other items than Textbooks so this works just as wanted. Thanks!
0

I'm assuming the array must have been created with type of Book. Therefore, you must cast the object to TextBook to get the course:

String textBookCourse = ((Textbook) books[i]).getCourse();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.