package Lessons;
public class Cube {
// TODO Auto-generated method stub
int length;
int width;
int heigtht;
//类方法
public int getCubeVolum(){
return(length*width*heigtht);
}
//构造函数,把变量的初始化和赋值放在了构造函数里面,然后在MyClass里面新建一个c1的对象,调用类中球体积的方法,得到了体积的值。主要明白,变量是从构造函数去初始化和赋值这个过程。
//定义一个参数为空的构造函数
Cube(){
length=10;
width=20;
heigtht=30;
}
//定义一个三个参数的构造函数
Cube(int l,int w,int h){
length=l;
width=w;
heigtht=h;
}
}
1 package Lessons;
2
3 public class MyClass {
4
5 public static void main(String[] args) {
6 // TODO Auto-generated method stub
7 Cube C1=new Cube();
8 Cube C2=new Cube(20,20,20);
9 System.out.println(C1.getCubeVolum());
10 System.out.println(C2.getCubeVolum());
11 }
12
13 }
总结:
类是对象的创建模板,所以,要创建一个对象实例,必须先要定义一个类。
构造函数的作用就是,每个该类的对象在创建过程就被初始化
构造函数还有一个特点,构造函数内部不能有返回语句,即构造函数没有返回值。
构造函数:
1)构造函数名称一定要和类名称保持一致。
2)构造函数会在对象创建过程是调用
3)构造函数可以有多个,用参数个数和参数类型区分
4)构造函数内部没有返回语句