How to use java method in programming


In this lesson, we will learn how to define Object methods. An Object is a Bundle of State And Behavior. Data Fields Define the State, Methods Define the behavior. Check out this program. The Rectangle class has fields width and height And A constructor. In the main method, A new Object is created

public class Main{
public static void main(String[] args){
Rectangle rect = new Rectangle(100,200);
}
}
class Rectangle{
int width;
int height;
Rectangle(int width, int height){
this.width= width;
this.height= height;
 }
}

we've added a method getWidth() to the Rectangle class. the method returns the value of the width field.

class Rectangle{
int width;
int height;
Rectangle(int width, int height){
this.width=width;
this.height=height;
}
//The Get Method
int getWidth(){
return this.width;
}
}

In the Main Method getWidth() is called on the New Rectangle Method with the dot notation. the object is passed implicitly as a parameter, which can be accessed by the keyword this inside the getwidth() method. Guess what the program prints?

public class Main{
public static void main(String [] args){
Rectangle rect = new Rectangle(100,200);
System.out.println(rect.getWidth());
}
}
 The getWidth() method returns  the value of 100 of the width field
now add a method getHeight() which returns The rectangle's height see the codes below

class Rectangle{
int width;
int height;
Rectangle(int width, int height){
this.width = width;
this.height = height;
}
//Get Height Method
int getHeight(){
return this.height;
}
//Get Width Method
getWidth(){
return this.width;
}
}
in the main method call getheight() and print the result

public static void main(String[] args){
Rectangle rect = new Rectangle(100,200);
System.out.println(rect.getWidth());
System.out.println(rect.getHeight());
}
}
Add a method getArea() which calculates and returns the Rectangle Area.

class Rectangle{
int width;
int height;

Rectangle(int width, int height){
this.width=width;
this.height=height;
}
//Get Height method
int getHeight(){
return this.height;
}
//Get Area Method
int getArea(){
return this.width*height;
}
//The Get Width Method
int getWidth(){
return this.width;
}
}
in the main method call the getArea() Method
and print the result

Post a Comment

0 Comments