java 类和构造方法
1.给对象的赋值
public class Test {
public static void main(String[] args) {
/********** Begin **********/
//创建Dog对象
//设置Dog对象的属性
Dog a=new Dog();
a.mz="五花肉";
a.maose="棕色";
a.pinz="阿拉斯加";
//输出小狗的属性
System.out.println("名字:"+a.mz+ ",毛色:" +a.maose+ ",品种:" + a.pinz );
//调用方法
a.Gou();
/********** End **********/
}
}
//在这里定义Dog类
/********** Begin **********/
class Dog
{
String mz,maose,pinz;
void Gou()
{
System.out.println("啃骨头");
System.out.println("叼着骨头跑");
}
}
这种方法不是很好,一般用构造方法赋值
2.构造方法赋值:
public class Test {
public static void main(String[] args) {
/********** Begin **********/
//创建Dog对象
//设置Dog对象的属性
Dog a=new Dog("五花肉","棕色","阿拉斯加");
//输出小狗的属性
System.out.println("名字:"+a.mz+ ",毛色:" +a.maose+ ",品种:" + a.pinz );
//调用方法
a.Gou();
/********** End **********/
}
}
//在这里定义Dog类
/********** Begin **********/
class Dog
{
String mz,maose,pinz;
public Dog(){
this.mz=mz,
this.maose=maose;
this.pinz=pinz;
}
void Gou()
{
System.out.println("啃骨头");
System.out.println("叼着骨头跑");
}
}
结果是一样。