Java构造方法

2020-11-05  本文已影响0人  放开好人
声明:本文为了梳理JAVA基础而整理,结合网络信息与个人理解汇聚而成,若不小心构成侵权,随时联系,随时删除。

一、构造方法定义

构造方法是一种特殊的方法,与类同名。创建对象也是通过构造方法完成,主要功能是完成对象的初始化。当类实例化对象时(new一个对象),将自动调用该类的构造方法。构造方法亦可重载。
在java中,必须先将任何变量设置为初始值,java提供了构造方法用于将初始值分配给类的成员变量。

class GouZao{
    GouZao(){ System.out.println("构造方法");}
    GouZao(String name){System.out.println("构造方法" + name); }
    GouZao(int a,int b){System.out.println(a + b); }
    void shuchu(){System.out.println("非构造方法"); }
}
public class TestGouZao {
    public static void main(String[] args) {
        GouZao gouZao = new GouZao();//输出“构造方法”
        gouZao.shuchu();
        GouZao gouZao1 = new GouZao("fangk");//输出“构造方法fangk”
        gouZao1.shuchu();
        GouZao gouZao2 = new GouZao(1,2);//输出3
        gouZao2.shuchu();
    }
}

二、特性

1. 作用:构造出来一个类的实例,并进行初始化。
2. 语法规则
3. 特点
4. 继承
class GouZaofu{
    GouZaofu(String name){ System.out.println("父类有参构造方法" + name); }
    GouZaofu(){System.out.println("父类无参构造方法"); }
}
class GouZaozi extends GouZaofu{
    GouZaozi(String name) {super(name); }
    GouZaozi(){}
}
public class TestGouZaofuzi {
    public static void main(String[] args) {
        GouZaozi gouZaozi = new GouZaozi();//输出 父类无参构造方法
        GouZaozi gouZaozi1 = new GouZaozi("fangk");//输出 父类有参构造方法fangk
    }
}
--------互相灵活调用----------------
class GouZaofu{
    GouZaofu(String name){ System.out.println("父类有参构造方法" + name); }
//    GouZaofu(){System.out.println("父类无参构造方法"); }
}
class GouZaozi extends GouZaofu{
    GouZaozi() {super("fangk"); }
//    GouZaozi(){}
}
public class TestGouZaofuzi {
    public static void main(String[] args) {
        GouZaozi gouZaozi = new GouZaozi();//输出 父类无参构造方法
//        GouZaozi gouZaozi1 = new GouZaozi("fangk");//输出 父类有参构造方法fangk
    }
}
上一篇 下一篇

猜你喜欢

热点阅读