java构造方法

2年前 (2022) 程序员胖胖胖虎阿
263 0 0
  1. 构造方法用来给类的成员声明初始化。
  2. 构造方法是一种特殊的方法,它的方法名与类名相同,并且没有返回值,也不需要使用void关键字修饰。
  3. 构造方法分为两种,无参构造器(默认构造方法)和有参构造器(自定义构造方法)

例:手动添加无参构造器的创建

public class Apple{
         String name;

          float apple;

           public Apple(){

                      name=苹果,

                      apple=12;

}

}

如果不想手动添加也可以不用添加系统会自动创建

public class Apple{
         String name;

          float apple;

           public Apple(){}

}

例:有参构造器的创建

public class Apple{
         int name;

          float apple;

           public Apple(int name, float apple){

                      this.name=name;

                      thise.apple=apple;

}

}

警告提示

如果类已经定义了一个或多个构造方法那么java,就不提供默认的构造方法。

修正方法

在拥有有参构造器的类中,手动添加无参构造器

public class Apple{
         int name;

          float apple;

        public Apple(){

                      name=苹果,

                      apple=12;

}

           public Apple(int name, float apple){

                      this.name=name;

                      thise.apple=apple;

}

}

 

 

 

版权声明:程序员胖胖胖虎阿 发表于 2022年9月22日 上午8:32。
转载请注明:java构造方法 | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...