Java中的类和对象

   

    Java中类和对象和C++中类似,只不过在具体使用的时候有几个地方需要额外注意的。这里我列出来,几个主要的,后面如果发现了,或者理解更加深入了,再添加。


    这篇博文还有一个重要的作用,就是确定Java编程的习惯,类在定义的时候该写什么注释,这些都要有一个较好的习惯。


1)一个java文件中,可以存在多个class,但是只能有一个public class + 和文件名相同的类名。这个类是主类,名字一定要定义的和文件名一致。

2)只能在主类中定义public static void main(string [] args) {}. 有main方法的才是主类,才能运行。

3)类在定义的时候,构造函数也是可以重载的。


    一个基础的代码如下:


/**
 * 
 * @author Powered by Zhu Yangping
 *
 */

class Circle {
	/**
	 * CIRCLE CLASS            注意格式
	 * 
	 * Data: radius
	 * 
	 * Functions: getCircum, getArea
	 */
	
	// data
	double radius; 
	
	// constructor function 1
	Circle() {
		radius = 1.0; 
	}
	
	// constructor function 2
	Circle(double newRadius) {
		radius = newRadius; 
	}
	
	// getCircum function
	double getCircum() {
		return 2 * radius * Math.PI; 
	}
	
	// getArea function
	double getArea() {
		return radius * radius * Math.PI; 
	}
}




public class TestCircle {

	/**
	 * @param args          注意格式
	 * 
	 * MAIN CLASS
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Circle circle1 = new Circle(); 
		System.out.println("The circum of circle1 is " + circle1.getCircum() + ", and its area is " + circle1.getArea()); 
		
		Circle circle2 = new Circle(25.0);
		System.out.println("The circum of circle1 is " + circle2.getCircum() + ", and its area is " + circle2.getArea());
		
		Circle circle3= new Circle(10);
		System.out.println("The circum of circle1 is " + circle3.getCircum() + ", and its area is " + circle3.getArea());
		
		
		
	}

}






  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值