Construction method is a special method, which has the same name as the class. The creation of objects is accomplished by constructing methods, whose function is mainly to complete the initialization of objects. The constructor is called automatically when the class instantiates an object. Construction methods can be overloaded as well as other methods.
class Cylinder //定义类Cylinder
{
private double radius;
private int height;
private double pi=3.14;
public Cylinder(double r, int h) //定义构造方法
{
radius=r;
height=h;
}
double area()
{
return pi* radius* radius;
}
double volume()
{
return area()*height;
}
}
public class Javase_09 //定义主类
{
public static void main(String[] args)
{
Cylinder volu=new Cylinder(3.5, 8); //创建对象并调用构造方法
System.out.println("圆柱底积="+ volu.area());
System.out.println("圆柱体体积="+volu.volume());
}
}