在构造方法中调用另一个构造方法(必须使用this语句调用)

狂风中的少年 提交于 2019-12-05 02:50:27
package DemoArea4.copy;

import org.omg.PortableServer.POAPackage.ServantAlreadyActive;

public class area4 {
	private int A;
	private int B;
	private String Color;
	
	public area4() {
		// 定义无参的构造方法
		this(2,6,"ls");
		System.out.println("无参方法被this调用");
		
	}
	
	public area4(int a,int b,String col) {
		// 定义有参的构造方法
		A=a;
		B=b;
		Color=col;
	}
	
	int showarea(){
		return A*B;
	}
	String showcolor(){
		return Color;
	}
	
}

  

package DemoArea4.copy;

public class Mainarea4 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		area4 a1=new area4();// 调用无参的构造方法
		area4 a2=new area4(3,6,"了LS");// 调用有参的构造方法
		
		System.out.println("A1"+a1.showarea());
		System.out.println("A1"+a1.showcolor());
		
		System.out.println("A2"+a2.showarea());
		System.out.println("A2"+a2.showcolor());
	}

}

  结果

无参方法被this调用
A112
A1ls
A218
A2了LS

  

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!