The tenth JAVA homework "Chapter 12 Static Attributes and Method Homework - Basic Definition and Use of Classes + static"

CG system URL: http://211.81.175.89

static modifier

  • static variable:

    The static keyword is used to declare static variables independent of objects. No matter how many objects a class instantiates, there is only one copy of its static variables. Static variables are also known as class variables. Local variables cannot be declared as static variables.

  • static method:

    The static keyword is used to declare a static method independent of the object. Static methods cannot use non-static variables of the class. Static methods get data from the parameter list, and then calculate these data.

Static variables are also called static variables. The difference between static variables and non-static variables is that static variables are shared by all objects and have only one copy in memory. They are initialized if and only when the class is first loaded . Non-static variables are owned by the object and are initialized when the object is created . There are multiple copies, and the copies owned by each object do not affect each other.
The initialization order of static member variables is initialized in the order in which they are defined.
 

On the basis of defining the rectangle class Rect in the previous "class and object assignment", add two static methods:

public static double getArea(double x,double y)

public static double getPerimeter(double x,double y)。

These two methods calculate the area and perimeter of a rectangle, respectively, based on the parameter values ​​received.

The code of the main method is as follows, pay attention, do not modify the code of the main method, otherwise the rebate points:


import java.util.Scanner;

class Rect {
    //类的属性
    double side1;
    double side2;

    //方法
    public static double getArea(double x,double y) {  //计算矩形的面积
        double area;  //定义面积变量
        area = x * y;
        return area;  //返回面积

    }

    public static double getPerimeter(double x,double y) {  //计算矩形的周长
        double per;  //定义周长变量
        per = (x + y) * 2;
        return per;  //返回周长
    }
    public double getArea(){  //计算矩形的面积
        double area;  //定义面积变量
        area = side1*side2;
        return area;  //返回面积

    }
    public double getPerimeter(){  //计算矩形的周长
        double per;  //定义周长变量
        per = (side1+side2) * 2;
        return per;  //返回周长
    }

}
public class one {
    public static void main(String[] args)
    {
        Scanner sin =new Scanner(System.in);
        Rect r = new Rect();
        r.side1 = sin.nextDouble();
        r.side2 = sin.nextDouble();

        System.out.println("area is:"+r.getArea());
        System.out.println("perimeter is:"+r.getPerimeter());
        System.out.println(Rect.getArea(3, 5));
        System.out.println(Rect.getPerimeter(3, 5));
    }
}

Guess you like

Origin blog.csdn.net/qq_25887493/article/details/123982421
Recommended