user3134939 user3134939 - 7 months ago 13
Java Question

Method access without creation of object

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();
}
}

Answer

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 l,int w){
    System.out.println(length*width);
}

public static void main(String args[]){  
    Rectangle.calculateArea(11,5); 
}  
}
Comments