1、构造函数定义
类中的构造函数用来初始化一个类。构造函数为公有类型,无返回值,用来从类实例中访问类时初始化此类的私有变量。
2、代码
public class UseConstruct
{
public static void main(String[] args)
{
Manager m=new Manager("王飞",10000,"业务部");
System.out.println(m.getSalary());
}
}
class Employee
{
private String name;
private int salary;
public Employee(String _name,int _salary)
{
name=_name;
salary=_salary;
}
public String getSalary()
{
String str;
str = "名字: " + name + "\n工资: " + salary;
return str;
}
} class Manager extends Employee
{
private String department;
public Manager(String _name,int _salary,String _department)
{
super(_name,_salary);
department=_department;
}
public String getSalary()
{
return super.getSalary()+"\n部门:"+department;
}
}
3、构造函数的理解
构造函数与类名相同
调用构造函数为类进行初始化赋值