• 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
  • 相关阅读:
    request.json 打印中文乱码解决
    看懂项目代码需要掌握的技能 (java语言)
    jmeter响应断言通过,结果树中却显示红色
    nginx的upstream后端名称居然变成了请求的host了?
    基于QRcode创建和识别二维码的研究
    thinkphp访问mysql中文字段问题
    apache https访问配置
    如何获得bibitem格式的参考文献
    CSharp: Image Matting
    word2vec回顾
  • 原文地址:https://www.cnblogs.com/evai/p/6035020.html
Copyright © 2020-2023  润新知