java之数据域封装set、get方法

复习package
javac Jpro\Circles3.java
javac Jpro\Demo032901.java
java Jpro.Demo032901
Cirlces3类的代码如下:

package Jpro;
public class Circles3{
    private double radius = 1;
    private static int numberOfObjects = 0;
    public Circles3(){
        numberOfObjects++;
    }
    public Circles3( double newRadius ){
        radius = newRadius;
        numberOfObjects++;
    }
    public double getRadius(){
        return radius;
    }
    public void setRadius( double newRadius ){
        radius = ( newRadius >= 0 )?newRadius:0;
    }
    public static int getNumberOfObject(){
        return numberOfObjects;
    }
    public double getArea(){
        return radius * radius * Math.PI;
    }
}

Demo032901.java主调函数类

package Jpro;
public class Demo032901{
    public static void main( String [] args ){
        Circles3 myCircle = new Circles3( 5.0 );
        System.out.println( " radius = " + myCircle.getRadius() );
        System.out.println( "area = " + myCircle.getArea() );

        myCircle.setRadius( ( myCircle.getRadius() +10)  );
        System.out.println( " radius = " + myCircle.getRadius() );
        System.out.println( "area = " + myCircle.getArea() );
        System.out.println( "the number of objects is " + Circles3.getNumberOfObject() );
    }
}

你可能感兴趣的:(java)