Classes in Java code exist in hierarchies. Classes above a given class in a hierarchy are superclasses of that class. That particular class is a subclass of every class higher up. A subclass inherits from its superclasses. The class Object is at the top of every class's hierarchy. In other words, every class is a subclass of (and inherits from) Object.
For example, suppose we have an Adult class that looks like this:
public class Adult {
protected int age = 0;
protected String firstname = "firstname";
protected String lastname = "lastname";
protected String gender = "MALE";
protected int progress = 0;
public Adult() { }
public void move() {
System.out.println("Moved.");
}
public void talk() {
System.out.println("Spoke.");
}
}
Our Adult class implicitly inherits from Object. That's assumed for any class, so you don't have to type extends Object in the class definition. But what does it mean to say that our class inherits from its superclass(es)? It simply means that Adult has access to the exposed variables and methods in its superclasses. In this case, it means that Adult can see and use the following from any of its superclasses (we have only one at the moment):
• public methods and variables
• protected methods and variables
• Package protected methods and variables (that is, those without an access specifier), if the superclass is in the same package as Adult.
Defining a class hierarchy:
Suppose we have another class called Baby. It looks like this:
public class Baby {
protected int age = 0;
protected String firstname = "firstname";
protected String lastname = "lastname";
protected String gender = "MALE";
protected int progress = 0;
public Baby() {
}
public void move() {
System.out.println("Moved.");
}
public void talk() {
System.out.println("Spoke.");
}
}
Our Adult and Baby classes look very similar. In fact, they're almost identical. That kind of code duplication makes maintaining code more painful than it needs to be. We can create a superclass, move all the common elements up to that class, and remove the code duplication. Our superclass could be called Person, and it might look like this:
public class Person {
protected int age = 0;
protected String firstname = "firstname";
protected String lastname = "lastname";
protected String gender = "MALE";
protected int progress = 0;
public Person() {
}
public void move() {
System.out.println("Moved.");
}
public void talk() {
System.out.println("Spoke.");
}
}
Now we can have Adult and Baby subclass Person, which makes those two classes pretty simple at the moment:
public class Adult {
public Adult()
{
}
}
public class Baby {
public Baby()
{
}
}
0 comments:
Post a Comment