Java 使用类的概念查找矩形的面积和周长

Java 使用类的概念查找矩形的面积和周长

Java语言是当前世界上最常用的面向对象编程语言之一。

的概念是面向对象语言中最重要的特性之一。一个 就像是一个对象的蓝图。例如,当我们想要建造一个房子时,我们首先会创建一个房子的蓝图,换句话说,我们创建一个展示我们将如何建造房子的计划。根据这个计划,我们可以创建多个房子。同样地,使用类,我们可以创建多个对象。一个类是创建多个对象的蓝图,其中对象是现实世界实体,如汽车、自行车、笔等。一个类具有对象的所有特性,而对象具有这些特性的值。在本文中,我们将编写一个Java程序,使用类概念来查找矩形的周长和面积。

一个类包括以下内容:

  • 数据成员 - 数据成员表示一组对象的特征/属性。

  • 方法 - 方法表示对象执行的操作。

例如,如果我们把一个人看作一个类,那么像姓名、年龄、地址这样的属性就是数据成员,而坐、站、吃、走这样一个人所做的操作就是类的方法。

创建一个类的语法

class ClassName
{
   //data members
   //methods
}

类名始终以大写字母开头。例如,Person(人)、House(房屋)、Bank(银行)等。

示例

class Person{
   //data members
   String name;
   int age;
   String city;
   //methods
   void read(){
      System.out.println(“Reading”);
   }
}

创建对象的语法

ClassName objectname = new ClassName();

示例

Person person_one =new Person();

矩形的周长

矩形的周长是由矩形的四条边所覆盖的总面积,即矩形的长度和宽度所覆盖的面积。

公式

Perimeter of the rectangle 
= area covered by the sides of the rectangle
= 2(l+w)
where,  l : length of rectangle
        w : width of rectangle

矩形的面积

矩形的面积是在二维平面内矩形所占据的总空间。

公式

Area of the rectangle 
= area covered by the rectangle
=  l*w
where , l : length of rectangle
             w : width of rectangle

步骤

步骤1 − 创建一个自定义类名为Rectangle,该类具有“area()”和“perimeter()”方法。这些函数将给出矩形的面积和周长作为输出。

步骤2 − 现在,在主类中使用构造函数创建一个Rectangle对象。

步骤3 − 现在,使用创建的对象调用相应的函数来找到矩形的面积和周长。

示例

在这个示例中,我们创建一个自定义的Rectangle类,该类具有“area()”和“perimeter()”方法。然后我们在主类中使用主类的构造函数创建一个Rectangle类的对象,并在创建的对象上调用相应的方法area()和perimeter()。一旦调用方法,它们将被执行并打印输出结果。

// Java program to calculate  the area and perimeter of a rectangle using class concept
import java.util.*;
// Rectangle Class File
class Rectangle {
    // data members
    int length, width;
    // methods
    //constructor to create Object
    Rectangle(int length, int width) {
        this. length = length;
        this.width = width;
    }
    // prints the area of rectangle
    public void area() {
        int areaOfRectangle;
        areaOfRectangle = this.length * this.width;
        System.out.println("Area of rectangle with the given input is : " + areaOfRectangle);
    }
    // prints the perimeter of rectangle
    public void perimeter() {
        int  perimeterOfRectangle;
        perimeterOfRectangle = 2 * (this.length + this.width);
        System.out.println("Perimeter of rectangle with the given input is : " + perimeterOfRectangle);
    }
}
public class Main {
    public static void main(String args[]) {
        Rectangle rect_obj = new Rectangle(10,5);  // obect creation
        System.out.println("Length = " + rect_obj.length);
        System.out.println("Width = " + rect_obj.width);
        rect_obj.area(); // returns area of rectangle
        rect_obj.perimeter(); //returns perimeter of rectangle
    }
}

输出

Length = 10
Width = 5
Area of rectangle with the given input is : 50
Perimeter of rectangle with the given input is : 30

时间复杂度:O(1) 辅助空间:O(1)

因此,在本文中,我们学习了如何使用类的概念实现Java代码来计算矩形的面积和周长。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程