Professional Documents
Culture Documents
Lab 02
Lab 02
Lab 02
Code re-use
• Achieved in java using
– Composition-
• define a new class, which is composed of existing
classes
– Inheritance
• derive a new class based on an existing class, with
modifications or extensions.
Create the following class
/*/The Author class model a book's author.
public class Author {
// The private instance variables
private String name;
private String email;
private char gender; // 'm' or 'f'
// The constructor
public Author(String name, String email, char gender) {
this.name = name;
this.email = email;
this.gender = gender;
}
// The public getters and setters for the private instance variables.
// No setter for name and gender as they are not designed to be changed.
public String getName() {
return name;
}
public char getGender() {
return gender;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
// The toString() describes itself
public String toString() {
return name + " (" + gender + ") at " + email;
}
}
/*
* A test driver for the Author class.
*/
public class TestAuthor {
public static void main(String[] args) {
// Test constructor and toString()
Author author = new Author("Abebe Kebede", "akeb@nowhere.com", 'm');
System.out.println(aKebede); // toString()
// Test Book's constructor and toString() // Using an anonymous Author instance to create a
Book instance
Book dummyBook = new Book("Java for dummies",
aKebede, 9.99, 99); Book moreDummyBook = new Book("Java for more
dummies",
System.out.println(dummyBook); // Book's
toString() new Author("Peter Lee", "peter@nowhere.com",
'm'), // an anonymous Author's instance
19.99, 8);
// Test Setters and Getters
System.out.println(moreDummyBook); // Book's
dummyBook.setPrice(8.88);
toString()
dummyBook.setQty(88);
}
System.out.println(dummyBook); // Book's
toString() }
System.out.println("name is: " +
dummyBook.getName());
Inheritance
• Extends the existing class called super class
• Use the extends keyword to indicate that
one class inherits from another
– The subclass inherits all the fields and methods of
the superclass
• Use the super keyword in the subclass
constructor to call the superclass constructor
– This ensures that the superclass part of the object
is constructed before the subclass part
Dog Cat
String name String name
int fleas int hairballs
String getName() String getName()
int getFleas() int getHairballs()
void speak() void speak()
using
inheritance
superclass
Animal
subclass
String name
subclass String getName()
Dog Cat
int fleas int hairballs
int getFleas() int getHairballs()
void speak() void speak() 10
The superclass Animal.java
public class Animal {
private String name;
public Animal(String n) {
name = n;
}
}
}