Java的构造方法,
分享于 点击 49114 次 点评:142
Java的构造方法,
Java中的基础知识。
构造方法是一种特殊的方法,它与所在类的名字相同。一旦定义好一个构造方法,创建对象时就会自动调用它。构造方法没有返回类型,一个类的构造方法的返回值的类型就是这个类本身。
构造方法的任务是初始化一个对象的内部状态。
构造方法初始化汽车的参数。
class Carr
{
private String color;
private String brand;
public Carr() //构造方法不带参数
{
this.color = "黑色";
this.brand = "奥迪";
}
public Carr(String co, String br) //构造方法携带两个参数
{
this.color = co;
this.brand = br;
}
public String getColor()
{
return this.color;
}
public String getBrand()
{
return this.brand;
}
}
public class Car {
public static void main(String args[])
{
Carr c = new Carr();
System.out.print("c:" + c.getColor());
System.out.println(c.getBrand());
Carr ca = new Carr("红色","BMW");
System.out.print("ca:" + ca.getColor());
System.out.println(ca.getBrand());
}
}
输出:
c:黑色奥迪
ca:红色BMW
private类型只能在自己类中被访问。
class Desk
{
private int width;
private int height;
public void setProperty(int i, int j)
{
if( i > 0)
width = i;
if(j > 0)
height = j;
System.out.println("设置宽高成功。宽"+width +"高" + height);
}
}
public class Sample {
public static void main(String args[])
{
Desk d = new Desk();
//d.width = 50; 不行,width是私有变量,只能在自己类中被访问
//d.height = 60;
d.setProperty(50, 60);
}
}
运行结果:
设置宽高成功。宽50高60
相关文章
- 暂无相关文章
用户点评