构造函数,重载

 构造函数

构造函数是一种特殊的函数,和类同名。其主要作用是用来创建对象时初始化对象,即为对象成员赋初值。可以重载多个不同的构造函数。

特征:

1. 方法名必须与类名相同

2. 构造函数没有返回值,在构造函数前面不声明方法类型

3. 一个类可以定义多个构造函数,如果定义类时没有定义构造函数,编译系统会默认插入一个无参数的构造函数。

4, 构造函数总是伴随着new一起调用

5. 不同的构造函数和不同的参数就叫做重载

实例1:

package study.stage1;

/**
* Created by Sandy.Liu on 2017/6/26.
*/
public class ConstructorDemo {
String name;
int age;

//创建一个了没有输入参数的构造函数
ConstructorDemo(){
System.out.println("I am a constructor without parameter");
}

//创建一个有输入参数的构造函数
ConstructorDemo(String myName,int myAge){
this.name = myName;
this.age = myAge;
System.out.println("i am a constructor with parameter");
System.out.println("my name is: "+name+" my age is: "+age);
}
}


构造函数不能继承,如果想要使用父类的构造函数,可以使用super关键字。无参数的构造函数不需要super调用,new新的实例的时候就会调用。
实例2:
package study.stage1;

/**
* Created by Sandy.Liu on 2017/6/26.
*/
public class ConstructorDemoExtend extends ConstructorDemo{
String name = null;

public static void main(String[] args){
ConstructorDemoExtend constructorDemoExtend = new ConstructorDemoExtend();
System.out.println("测试子类调用父类的无参构造函数");
}
}

输出的结果是:

I am a constructor without parameter
测试子类调用父类的无参构造函数

实例3:调用父类带参数的构造函数需要使用super

package study.stage1;

/**
* Created by Sandy.Liu on 2017/6/26.
*/
public class ConstructorDemoExtend extends ConstructorDemo{
ConstructorDemoExtend(){
super("sandy",300);
}

public static void main(String[] args){
System.out.println("测试子类调用父类带参数的构造函数");
ConstructorDemoExtend constructorDemoExtend = new ConstructorDemoExtend();
}
}

运行结果:

测试子类调用父类带参数的构造函数
i am a constructor with parameter
my name is: sandy
my age is: 300



原文地址:https://www.cnblogs.com/xiaohai2003ly/p/7080690.html