Java 中的构造方法

首先创建一个Transport类,定义好类的属性和方法,并且写好构造方法,先看下无参数的构造方法:

public class Transport {
    //名字
    public String name;
    //运输类型
    public String type;

    public void todo()
    {
        System.out.println("交通工具可以载人载物");
    }
    public Transport()
    {
        System.out.println("无参数的构造方法执行了");
    }
}

接着实例化Transport类:

public static void main(String[] args)
{
    Transport Plane = new Transport(); //输出 无参数的构造方法执行了
}

再来看下有参数的构造方法:

public Transport(String myName, String myType)
    {
        name = myName;
        type = myType;
        System.out.println("有参数的构造方法执行了,参数:"+name+","+type);
    }

实例化输出:

public static void main(String[] args)
{
    Transport Plane = new Transport("飞机", "空运"); //有参数的构造方法执行了,参数:飞机,空运
}

如果父类是带参数的构造方法子类也必须和父类一样使用带参数的构造方法并使用super()方法调用父类的构造函数,子类继承父类并调用父类属性和方法:

public class Plane extends Transport {public void todo()
    {
        System.out.println(name+"是最快的交通工具");
    }
    public Plane(String myName, String myType)
    {
        super(myName,myType);
    }
    public void test()
    {
        super.todo();
    }
}

实例化输出:

public static void main(String[] args)
{
    Plane plane = new Plane("飞机", "空运");  //这里执行的是super(myName,myType),输出 有参数的构造方法执行了,参数:飞机,空运
        plane.todo(); //飞机是最快的交通工具
        plane.test(); //交通工具可以载人载物
}
//输出结果为:

有参数的构造方法执行了,参数:飞机,空运
子类实例化参数:飞机空运300
飞机是最快的交通工具
交通工具可以载人载物

总之,子类如果有自己的构造方法,它的参数不能少于父类的参数,但是可以添加子类自己新的构造参数,如:

public Plane(String myName, String myType, int speed)
    {
        super(myName,myType);
        System.out.println("子类实例化参数:"+myName+myType+speed);
    }
Plane plane = new Plane("飞机", "空运", 300);

有参数的构造方法执行了,参数:飞机,空运
子类实例化参数:飞机空运300
原文地址:https://www.cnblogs.com/evai/p/6035020.html