编写Java类,其中有两个整形数据成员n1和n2,应声明为私有。编写构造方法,赋予n1和n2初始值,再为该类定义加、减、乘、除等公有成员方法,分别对两个成员变量执行加、减、乘、除的运算。

public class Number {
	private int n1;
	private int n2;
	public Number() {}
    public Number(int n1, int n2) 
    {
	    this.n1 = n1;
	    this.n2 = n2;
	}
	public int getN1() {
		return n1;
	}
	public void setN1(int n1) {
		this.n1 = n1;
	}
	public int getN2() {
		return n2;
	}
	public void setN2(int n2) {
		this.n2 = n2;
	}
	public void add()
	{
		System.out.println("加法:"+(n1+n2));
	}
	public void sub()
	{
		System.out.println("减法:"+(n1-n2));
	}
	public void mul()
	{
		System.out.println("乘法:"+(n1*n2));
	}
	public void div()
	{
		if(this.n2==0)
			System.out.println("被除数不能为0");
		else 
			System.out.println("除法:"+(double)(n1)/(double)(n2));
	}
	public static void main(String[] args) {
		Number number=new Number(4,3);
		number.add();
		number.sub();
		number.mul();
		number.div();
	}

}

你可能感兴趣的:(Java,java,开发语言)