Instance variables, static variables, instance methods and static methods, JavaSE

1. Introduction

The static variable numberOfObjects counts the number of Circle objects created. When the first object of the class is created, the value of numberOfObjects is 1. When the second object is created, the value of numberOfObjects is 2. The Circle class defines the instance variable radius and the static variable numberOfObjects, as well as the instance method getArea and the static method getNumberOfObjects.
Instance methods (for example: getAreaO) and instance data (for example: radius) belong to the instance, so they can be used after the instance is created. They are accessed by referencing variables. Static methods (for example: getNumberOfObjectsO) and static data (for example: numberOfObjects) can be called by referencing variables or their class names

2. Code

Implementation class

package com.zhuo.demo;

import com.zhuo.base.Circle;

public class CircleWithOfMenbers {
    
    
    double radius;
    static int numberOfObjects;
    CircleWithOfMenbers() {
    
    
        radius = 1;
        numberOfObjects++;
    }
    CircleWithOfMenbers(double newradius) {
    
    
        radius = newradius;
        numberOfObjects++;
    }
    int getNumberOfObject() {
    
    
        return numberOfObjects;
    }
    double getArea() {
    
    
        return radius * radius * Math.PI;
    }
}

Test class

package com.zhuo.demo;

public class TestCircleWithOfMenbers {
    
    
    public static void main(String[] args) {
    
    
        System.out.println("创建对象之前");
        System.out.println("圆对象的数量为: " + CircleWithOfMenbers.numberOfObjects);
        CircleWithOfMenbers c1 = new CircleWithOfMenbers();
        System.out.println("创建对象c1之后");
        System.out.println("c1半径为" +  c1.radius + ",面积为: " + c1.getArea() + ",圆的对象数为: " + c1.getNumberOfObject());
        CircleWithOfMenbers c2 = new CircleWithOfMenbers(5);
        c1.radius = 9;
        System.out.println("创建对象c2和修改c1之后");
        System.out.println("c1半径为" +  c1.radius + ",面积为: " + c1.getArea() + ",圆的对象数为: " + c1.getNumberOfObject());
        System.out.println("c2半径为" +  c2.radius + ",面积为: " + c2.getArea() + ",圆的对象数为: " + c2.getNumberOfObject());
    }
}

Three. Results display

创建对象之前
圆对象的数量为: 0
创建对象c1之后
c1半径为1.0,面积为: 3.141592653589793,圆的对象数为: 1
创建对象c2和修改c1之后
c1半径为9.0,面积为: 254.46900494077323,圆的对象数为: 2
c2半径为5.0,面积为: 78.53981633974483,圆的对象数为: 2

Process finished with exit code 0

Guess you like

Origin blog.csdn.net/weixin_42768634/article/details/113817229