Keep Things Simple with Java Classes

Most computer programs operate entirely in the virtual realm. They have no bricks, nails, or girders. So you can type a fairly complicated computer program in minutes. Even with no muscle and no heavy equipment, you can create a structure whose complexity rivals that of many complicated physical structures. You, the developer, have the power to build intricate, virtual bridges.

One goal of computer programming is to manage complexity. A good app isn't simply useful or visually appealing — a good app's code is nicely organized, easy to understand, and easy to modify.

Certain programming languages, like C++, support multiple inheritance, in which a class can have more than one parent class. For example, in C++ you can create a Book class, a TeachingMaterial class, and a Textbook class. You can make Textbook extend both Book and TeachingMaterial.

This feature makes class hierarchies quite flexible, but it also makes those same hierarchies extremely complicated. You need tricky rules to decide how to inherit the move methods of both the computer's Mouse class and the rodent's Mouse class.

To avoid all this complexity, Java doesn't support multiple inheritance. In Java, each class has one (and only one) superclass. A class can have any number of subclasses. You can (and will) create many subclasses of Android's Activity class.

And other developers create their own subclasses of Android's Activity class. But classes don't have multiple personalities. A Java class can have only one parent. The Executive class referred to in this listing cannot extend both the FullTimeEmployee class and the PartTimeEmployee class.

package org.allyourcode.company;
public class Executive extends FullTimeEmployee {
  double bonus;
  public Executive() {
  }
  public Executive(String name, String jobTitle,
                   double salary, double bonus) {
    this.name = name;
    this.jobTitle = jobTitle;
    this.salary = salary;
    this.bonus = bonus;
  }
  @Override
  public double pay() {
    return salary + bonus;
  }
}
  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com