-1

I am new to Java, and learning java through online tutorial. i have a sample program, i just want to know is there any other way to execute method of a class other then creation of new object, please check below program.

class Rectangle{ 

    int length;  
    int width; 

    void insert(int l,int w){  
        length=l;  
        width=w;  
    } 

    void calculateArea(){
        System.out.println(length*width);
    } 

    public static void main(String args[]){  
        Rectangle r1=new Rectangle();  
        Rectangle r2=new Rectangle();  
        r1.insert(11,5);  
        r2.insert(3,15);  
        r1.calculateArea();  
        r2.calculateArea();  
    }  
}
Michael
  • 776
  • 4
  • 19

2 Answers2

0

You can do something like defining static methods, such practice can be good IF YOU don't need an instance of the class to call some methods.

think about it like the Math.class in Java.

Example:

class Rectangle {  
    static void calculateArea(int length, int width) {
        System.out.println(length * width);
    }
  
    public static void main(String args[]) {  
        Rectangle.calculateArea(11, 5); 
    }  
}
Community
  • 1
  • 1
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
-1

The answer is yes. static functions are 'class method' and so could be called without an object (that is an instance of a class)

**

EXAMPLE:

class Languages {
  public static void main(String[] args) {
    Languages.display();
  }

  static void display() {
    System.out.println("Java is my favorite programming language.");
  }
}

**

For more about the difference between class and instance method read here

For more about what is an object read here

Community
  • 1
  • 1
granmirupa
  • 2,780
  • 16
  • 27