zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    Change OL3 drawing cursor (blue circle)
    解决Bootstrap's dropdowns require Popper.js
    bootstrap-table 如何获得服务器返回的json数据中的二级数组
    The database returned no natively generated identity value
    控制台报错:java.lang.ClassNotFoundException: javax.xml.bind.JAXBException之解决方法
    Tomcat起不来解决方法(the selection cannot be run any server & unable to start within 45 seconds)
    mysql语句优化
    mysql_知识点整理
    web.xml文件的作用及基本配置(转)
    资深高手谈接外包项目
  • 原文地址:https://www.cnblogs.com/evai/p/6035020.html
Copyright © 2011-2022 走看看