Java中的构造器、重载
构造器
-
构造器:又称构造方法,constructor
-
构造器用于构造该类的实例。
-
格式如下:
[修饰符] 类名 (形参列表){
// n条语句
} -
是一种特殊的方法:
通过new关键字调用!!
构造器虽然有返回值,但是不能定义返回类型(返回值的类型肯定是本类),不能在构造器里调用return。
如果我们没有定义构造器,则系统会自动定义一个无参的构造函数。如果已经定义则编译器不会添加!
构造器的方法名必须和类名一致! -
作用:构造该类的对象,经常也用来初始化对象的属性
public class Student {
// 静态的数据
String name;
int id; // 学号
int age;
String gender;
int weight;
Computer computer;
// 动态的行为
public void study(){
System.out.println(name+"在学习");
}
public void sayHello(String sname){
System.out.println(name+"向"+sname+"说:你好!");
}
}
public class Test1 {
public static void main(String[] args){
// 通过类加载器Class Loader加载Student类。加载后,在方法区中就有了Student类的信息!
Student s1 = new Student();
s1.name = "张三";
s1.study();
s1.sayHello("李四");
Student s2 = new Student();
s2.age = 18;
s2.name = "老高";
}
}
重载
-
方法的重载是指一个类中可以定义有相同的名字,但参数不同的多个方法。调用时,会根据不同的参数表选择对应的方法
-
两同三不同
–同一个类,同一个方法名
–不同:参数列表不同(类型,个数,顺序不同) -
只有返回值不同不构成方法的重载
-
只有形参的名称不同,不构成方法的重载
-
与普通方法一样,构造方法也可以重载
/**
* 测试重载
* @author null
*/
public class TestOverload {
public int add(int a,int b){
return a+b;
}
public static void main(String[] args){
MyMath m = new MyMath();
int result = m.add(4,5,8);
System.out.println(result);
}
}
class MyMath{
int a;
int b;
public MyMath(){
}
public MyMath(int a){
this.a = a;
}
public MyMath(int b,int a){
this.b = b;
this.a = a;
}
public int add(int b,double a){
return (int)(a+b);
}
public int add(double a,int b){
return (int)(a+b);
}
public int add(int a,int b){
return a+b;
}
public int add(int a,int b,int c){
return a+b+c;
}
}