| |home| |
Object-Oriented Programming ConceptExamples |
Let's recap. Everything can be described as an object. Every object has characteristics or states. The relationships are the structure of the object. has-a relationship can be described in Java code as member fields. is-a relationship can be described in Java keyword extends. The is-a relationship has an inheritance feature (like "extends" or "implements") and has-a relationship has an encapsulation feature (like private or protected modifier used before each member field or method).
Let's look at some examples. Translate the following perfect sentences into Java code.
public class Pizza extends Food {//is-a relationship
int ingredients;//has-a relationship
double cost;
double price;
....
}
|
public class Car extends Vehicle {//is-a relationship
String make; //has-a relationship
int model;
Date year;
String motor;
....
}
|
public class Dog extends Animal {//is-a relationship
String name;//has-a relationship
Color clr;
double weight;
boolean sex;
....
}
|
public class Iowa extends State {//is-a relationship
double budget;//has-a relationship
String department;
String division;
int stateCode;
....
}
|
A reader's comments:
It would be better to make Iowa an instance of State:
public class State {
String stateName;
double budget;
String department;
String division;
int stateCode;
}
State iowa, california, newYork, texas, washinton;
Or if State must be a super class, to make a subclass:
public class UrbanState extends State
public class RuralState extends State
public class InteriorState extends State
public class BorderState extends State
public class SavingsAccount extends BankAccount {//is-a relationship
int transitNumber; //has-a relationship
int accountNumber;
String name;
String address;
double accountBalance;
String accountStatus;
....
}
|
If you can tell difference or relationships between the Java code and the perfect sentences, you are on the right track in an object-oriented design and programming.
One more example here: Translate the following sentence into professional terms.
The heart of object-oriented programming is that one object can be composed of, or built from other objects. |
Answer: "composed of" means "has-a" relationship and can be described as member fields or object composition. "built from" means "is-a" relationship, and can be described in Java keywords "extends" or "implements".
Understanding "is-a" and "has-a" relationship is a key to open your door to the object-oriented programming.