JAVA构造方法、重载
1、JAVA构造方法——为对象赋初值
java的构造方法一般不用定义系统也会默认定义,只不过方法里是空的,不会执行任何操作。
构造方法特点:
a.没有返回值(void类型算是有返回值的,这里的没有返回值指的是什么类型都不能定义)
b.可重载
c.在实例化对象时自动调用
d.构造方法名与类名相同
构造方法作用:
在实例化对象时给对象的属性赋初值
2、JAVA重载
java中的方法名可以相同,但是参数不同,调用时会根据参数的不同而调用不同的方法
class Student
{
int age;
String name;
String sex;
Student(){
}
Student(int age1){ //构造方法与类名一样,无返回值 ,调用:在new的时候自动被调用
age=age1;
}
Student(int age1,String name1){
age=age1;
name=name1;
}
Student(int age1,String name1,String sex1){
age=age1;
name=name1;
sex=sex1;
}
void printInformation(){
System.out.println("姓名:"+name+" 年龄:"+age+" 性别"+sex);
}
}
public class Dome1 {
public static void main(String[] args){
Student stu1=new Student();
Student stu2=new Student(100);
Student stu3=new Student(99,"小明");
Student stu4=new Student(98,"小红","女");
stu1.printInformation();
stu2.printInformation();
stu3.printInformation();
stu4.printInformation();
}
}
3.UML类图
“+”表示public
“-”表示private
“#”表示protected