Monday, 17th October 2011
Follow WikiJava on twitter now. @Wikijava

Simplest example with a new object

From WikiJava

Jump to: navigation, search
The author suggests:

buy this book


There's no simpler example about java objects I could imagine.

Contents

the article

Let's suppose we would like to rappresent a rectangle, made from coordinates x = 5 and y = 10, height = 20 and width = 30. Then we would like to move it 15 units on the x axis, and 25 units on the y axis.

In Java we have a huge number of built-in completely-portable classes along with their methods. One of them rappresent a rectangle (when you write "import java.awt.Rectangle;"), with a lot of methods.

The Rectangle class describes both how to construct a rectangle with desidered values and an instance method called translate to move the rectangle (and many others built-in methods).

Il metodo translate ha due parametri formali che rappresentano lo spostamento lungo l'asse x e quello lungo l'asse y.

So we have to write a program who:

  • create a rectangle (a particular rectangle with that dimensions)
  • print/dump to the screen the rectangle status
  • move the rectangle 15 units on the x axis, and 25 units on the y axis
  • print/dump to the screen the rectangle status (to verify the change)

In other words we have to write something like this:

MoveRectangle.java

import java.awt.Rectangle;
 
public class MoveRectangle {
 
    public static void main(String[] args) {
        Rectangle rect;
        rect = new Rectangle(5, 10, 20, 30);
        System.out.println(rect);
        rect.translate(15, 25);
        System.out.println(rect);
   }
 
}


See Also

http://java.sun.com/javase/6/docs/api/java/awt/Rectangle.html

Comments from the users

To be notified via mail on the updates of this discussion you can login and click on watch at the top of the page


Comments on wikijava are disabled now, cause excessive spam.