TurkuBasicOOPinJava / Week 5: Class hierarchies /03B. Thesis inherits book
KaiquanMah's picture
Create 03B. Thesis inherits book
f4103cc verified
raw
history blame
2.89 kB
The program defines the class 'Book'.
An object can be created from a class by giving it a name and an author as follows:
Book b = new Book("Old Man and the Sea", "Ernest Hemingway");
Write the class 'Thesis', which inherits the class Book.
The class has the following properties:
A constructor that takes as parameters the name, the author, and the grade (integer).
The constructor sets the name and author by calling the parent class constructor.
The grade is an attribute of the Thesis class.
Set and get methods for grade
import java.util.Random;
public class Test{
public static void main(String[] args){
final Random r = new Random();
String[] authors = {"Sam Student", "Sally Student", "Alex Average",
"Ethan Excellent", "Fiona Flunked"};
String[] names = {"Thesis", "Term Paper", "Masters thesis"};
for (int testi=1; testi<=3; testi++) {
String author = authors[r.nextInt(authors.length)];
String name = names[r.nextInt(names.length)];
Thesis lt = new Thesis(name, author, r.nextInt(5) + 1);
System.out.println("Thesis object created!");
Book k = (Book) lt;
System.out.println("Author: " + k.getAuthor());
System.out.println("Name: " + k.getName());
System.out.println("Grade:" + lt.getGrade());
System.out.println("Changing grade...");
if (r.nextInt(2) == 0) {
lt.setGrade(lt.getGrade() - 1);
} else {
lt.setGrade(lt.getGrade() + 1);
}
System.out.println("Grade:" + lt.getGrade());
System.out.println("");
}
}
}
class Book {
private String name;
private String author;
public Book(String name, String author) {
this.name = name;
this.author = author;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
class Thesis extends Book {
//subclass attributes
private int grade;
//constructor
public Thesis(String name, String author, int grade) {
super(name, author);
this.grade = grade;
}
public int getGrade() {
return this.grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
}
Thesis object created!
Author: Sam Student
Name: Masters thesis
Grade:1
Changing grade...
Grade:2
Thesis object created!
Author: Sam Student
Name: Masters thesis
Grade:1
Changing grade...
Grade:2
Thesis object created!
Author: Alex Average
Name: Term Paper
Grade:1
Changing grade...
Grade:0