My other sites
O










Java and Object Orientation

  The Object Model

Creating and Using Objects

Example of a Class and its Instance

Constructors

Methods

Calling Methods

Inheritance

Inheritance Example

Abstract

Interfaces
 

 

The Object Model

Is a view of the world in terms of Objects and their
relationships

Why we need it ?

Creating and Using Objects

To create a custom object in Java we need to:

- Create its class

- Instantiate an object from the class using : new

 

Example of a Class and its Instance

class Star {
}

public class TestStar {

   public static void main(String[] argv) {
      Star my_star;
      my_star = new Star() ;
   }
} 


Constructors

class Star {
   int edges;

   public Star(int _edges) {
      edges=_edges;
   } 
}

public class TestStar {
    public static void main(String[] argv) {
        Star first_star,second_star;
        first_star = new Star(5) ;
        second_star = new Star(7);
    }
}

 

Methods

class Star {
   //state, data 
   int edges_num=3; 

   //methods, behaviour
   public Star(int _edges) {
      edges_num =_edges;
   }

   public void setEdges(int _edges){
      edges_num=_edges;
   }

   public int getEdges() {
      return edges_num;
   } 
}
Is the constructor a method?



Calling Methods

public class TestStar {

   public static void main(String[] argv) {

      Star first_star,second_star;
      first_star = new Star(5) ;
      second_star = new Star(7);
      first_star.setEdges(10);
      second_star.setEdges(14);
      System.out.println("1st Star:" + first_star.getEdges());
      System.out.println("2nd Star:" + second_star.getEdges());
   }
}


Inheritance

A class can..

specialise,

extend,

subclass, or

be a child of another class.

Do you know other terms?

 


Inheritance Example

class Shape {
   protected int edges_num; 
}
class Star extends Shape {
    Star(int _edges) {
       edges_num = _edges;
    }
}
public class TestStar {
    public static void main(String[] argv) {
        Star my_star;
        my_star = new Star() ;
    }
}


Abstract

Abstract classes :

cannot be instantiated

Abstract methods :

1. cannot have any implementation

2. need implementation
from their children

abstract class Shape {
   protected int edges_num; 
   abstract void draw(); 
}
class Star extends Shape{
   Star(int _edges) {
      edges_num = _edges;
   }
   public void draw() {
   }
}

Interfaces

- are special kinds of abstract classes

- cannot have any implementation

- must be implemented by the classes that use them

- cannot be compared with C++'s multiple inheritance

- sometimes they are used to "tag" instances

- usually have an -able ending (Cloneable, Drawable etc)

interface Drawable {
   public void draw() ;
}
class Star extends Shape 
implements Drawable{ public void draw() { } }