I am completing a homework assignment for a Java programming course and I am having trouble understanding the concept of a subclcass.
Here is the question:
Create a class named Book that contains data fields for the title and number of pages. Include get and set methods for these fields. Next, create a subclass named Textbook, which contains an additional field that holds a grade level for the Textbook and additional methods to get and set the grade level field. Write an application that demonstrates using objects of each class. Save the files as Book.java, Textbook.java, and DemoBook.java.
Here is my code for Book.java:
public class Book
{
String bookTitle;
int numPages;
private void setBTitle(String title)
{
bookTitle = title;
}
private void setBPages(int pages)
{
numPages = pages;
}
private String getBTitle()
{
return bookTitle;
}
private int getBPages()
{
return numPages;
}
public void displayBookInfo()
{
System.out.println("The book's title is: " + bookTitle + ".");
System.out.println("The number of pages is: " + numPages + ".");
}
}
Here is my code for Texbook.java:
public class Textbook extends Book
{
int gradeLevel;
public int getGLevel()
{
return gradeLevel;
}
public void setGLevel(int level)
{
gradeLevel = level;
}
}
If I do in fact have those two parts correct, how would I implement this in a DemoBook.java file?
Any help or direction would be appreciated.
Here is my code for the DemoBook.java file:
import java.util.Scanner;
public class DemoBook
{
public static void main(String[] args)
{
String BTitle;
int BPages;
int BLevel;
Book b = new Book();
Textbook t = new Textbook();
Book bt = new Textbook();
Scanner input = new Scanner(System.in);
System.out.println("Please enter the title of your book: ");
BTitle = input.nextLine();
System.out.println("Please enter the number of pages: ");
BPages = input.nextInt();
System.out.println("Please enter the grade level: ");
BLevel = input.nextInt();
b.setBTitle(BTitle);
b.setBPages(BPages);
t.setGLevel(BLevel);
b.displayBookInfo();
}
}
I changed the variables to private, and this is the compiler error I get:
DemoBook.java:33: error: setBTitle(String) has private access in Book
b.setBTitle(BTitle);
^
DemoBook.java:34: error: setBPages(int) has private access in Book
b.setBPages(BPages);
^
2 errors
I am still not grasping this. The chapter is titled Introduction to Inheritance.
DemoBook.javais to be the "application that demonstrates using objects of each class".