java构造方法
1.构造方法的定义:
构造方法是类在生成对象时,系统自动调用的方法(如果类中未声明构造方法,则调用默认的构造方法:new 类名();
2.构造方法目的:
构造方法是为了实现特定对象的实例化过程
eg:
public class gouzao1 {
public static void main(String[] args){
student s = new student();//调用无参的构造方法,输出结果为:无参构造方法
student s1 = new student(2,"chang");//调用两个参数的构造方法
student s2 = new student(2);//编译出错,因为构造方法前用private修饰,private代表的是私有,只在本类中有效
//System.out.println(s);//输出的为new student()在堆内存中的地址
}
}
class student
{
private student(int age)
{
System.out.println("传递一个参数的构造方法!");
}
public student()
{
System.out.println("无参构造方法!");
}
student(int age,String name)
{
System.out.println("两个参数的构造方法!");
}
student(String name,int age)
{
System.out.println("和上面那个是不同的构造方法!");
}
}
在上例中,student为类student;s是引用变量,代表对象的引用;new student()是调用无参的构造方法。
在对象初始化时,各个数据在内存中空间的分配是这样的:首先,在栈内存中划分一个区域,存放引用变量s,其次在堆内存中划分区域存放new student();并将new 生成的对象的地址赋给s,这样s就指向new生成的对象了。上例中,注释掉的部分System.out.println(s),输出为student@1c78e57,代表的就是在内存中的地址。
3.构造方法的禁忌:
a.构造方法通常用public或default修饰(用private修饰无法生成对象,如上。用protected修饰只能在一个包一个类,子类中使用);
b.构造方法名必须与类名相同;
c.构造方法没有返回值类型,void也不行;
d.构造方法可以有任意多个参数;
e.构造方法中参数相同,顺序不同,是不同的构造方法!
4.构造方法的重载现象;
同名的参数不同的构造方法共存的现象;
5.构造方法之间的调用;
eg:
class student
{
student(int age)
{
System.out.println("传递一个参数的构造方法!"+ age);
}
protected student()
{
System.out.println("无参构造方法!");
}
student(int age,String name)
{
this(age);//调用一个参数的构造方法,!!!此时this(),必须为第一行!!!
System.out.println("两个参数的构造方法!");
}
}
输出结果为:
无参构造方法!
传递一个参数的构造方法!2
两个参数的构造方法!
6.继承中的构造方法:
详情见下一篇;
Java构造方法详解


1188

被折叠的 条评论
为什么被折叠?



