Você está na página 1de 3

Code Management

Chapter 5
Code Management

Object Oriented Programming provides better way to manage code, so one can
build and maintain application of any size and complexity using object oriented concepts.
An application could be built in several ways.
An application may be a collection of several objects.
Object itself may contain other objects
Object may be created from existing objects
Several objects may be using same interface for doing same thing or different
thing.
Code management in java can be accomplished through inheritance, composition,
and polymorphism.
Object class
All java class has single rooted class hierarchy that starts from java.lang.Object.
The class you create has one implicit parent, Object if your class was not explicitly sub-
classed.

class Stock{
private int stock;
public Stock(int stock){
this.stock=stock;
}
}

The hierarchy of class Stock:


Stock Objec

class Stock{
private int stock;
public Stock(int stock){
this.stock=stock;
}
}

class StockManager extends Stock{


}

tURBOPLUS
Code Management

The hierarchy of class StockManager:


StockManag Stock Objec
er
Basically java support single inheritance, however when you look at the above
diagram it is very clear that one can create different levels of classes. Since it is begins
from single rooted hierarchy; one can form a tree like structure rooted on Object class.
Inheritance provides complete code re-usability, however one does not want; he
can override the required methods to shape the class in new way.
Another way of re-usability is through composition. When you develop an
application in java you are using inheritance and composition.
Dynamic method dispatch
Interface methods are used for dynamic method dispatch. Selection of the method
to be executed is at runtime. Each implementation varies from class to class (code
organization).

public interface Shape{


void draw(Dimensio d);
}
public class Rect{
void draw(Dimensio d){
//code
}
}
public class Circle{
void draw(Dimensio d){
//code
}
}
public class Line{
void draw(Dimensio d){
//code
}
}
public class Elipse{
void draw(Dimensio d){
//code
}
}
public class App{
public static void main(String[] args){

Shape[] shapes{new Rect(),new Circle(),new Line(),new Elipse()};


}
}

tURBOPLUS
Code Management

The above program shows dynamic method dispatch, where shapes[i].draw() will be
solved only at run-time.

tURBOPLUS

Você também pode gostar