Nicolas
Nicolas

Reputation: 63

Java Call Method of Class Object In Array

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?

Upvotes: 0

Views: 2438

Answers (2)

unkhan
unkhan

Reputation: 278

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

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234795

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.

Upvotes: 3

Related Questions