Objects and methods The colored to comment. |
|
I. Introduction Let's consider the following example: Class rectangle: In this class, where we make acquaintance with an object (here Rectangle),we introduce: An object that are known as instance of that class. A data type of variables (or instances), A constructor, Some instances (functions or methods), And a main function. Recall that: - The function main is static, because it is not a method that we involve an object itself. Inside this function, we call the constructor to build a concrete rectangle of certain width and length. - The function main needs always to be static in order to be compiled and public in order to be executed. class Rectangle { int width, length; //Statements declaring two local variables Rectangle (int w, int l){// Constructor of the object Rectangle , with the same name than the class width = w; length = l; } int Perimeter (){//First method return 2 * (width + length); } int Surface (){//Second method return width * length; } void Display (String Name1, String Name2){//Another method to display System.out.println("\n\t This is the first built " + Name1 + ". It is a " + Name2 + " with the following features: \n width = " + width + "\n length = " + length + "\n Perimeter = " + Perimeter ()+ "\n Surface = " + Surface ()+ "."); } public static void main (String[] args){//Main function Rectangle Rec = new Rectangle (15, 5);// Rec is a built rectangle Rec.Display ("object", "rectangle");// How to apply a method to an object } } Constructor Object = new Constructor (); Object.Method(); To compile: C:\Java>javac Rectangle.java To execute: C:\Java>java Rectangle This is the first built object. It is a rectangle with the following features: width = 15 length = 5 Perimeter = 40 Surface = 75. C:\Java> |