一、构造方法的使用
作用:创建对象并初始化对象
特点:
1)构造方法无返回值,不用写void
2)构造方法的方法名和类名相同
3)构造方法的结构:访问权限修饰符 类名(参数列表){方法体}
4)构造方法的参数列表根据有无参数分为无参构造和有参构造
1、无参构造器:
//这是无参构造器 public Account() { }
public class TestAccount { public static void main(String[] args) { //使用无参构造器构造对象并初始化 Account account = new Account(); account.name="jack"; account.balance=60; account.pwd="123456"; account.showInfo(); } }
2、有参构造器
//这是有参构造器 public Account(String name, double balance, String pwd) { this.name = name; this.balance = balance; this.pwd = pwd; }
public class TestAccount { public static void main(String[] args) { //使用有参构造器构造对象并初始化 Account account = new Account("Tom",1000,"123445"); account.showInfo(); } }
注:没有构造器时,系统会默认添加一个无参构造器。当自定义一个有参构造器时,系统默认的无参构造器会失效。如果仍要使用无参构造器,需要重新定义。避免有参构造器覆盖无参构造器,建议两个构造器同时写上(这里就实现了构造方法的重载)。
二、方法的重载
方法重载的原则:
1)同一个类中,方法名相同,参数列表不同(参数的数量、类型、顺序不同)
2)方法的重载与返回值类型无关
3)调用 时,根据方法参数列表的不同来区别。
public class Calculate { public static int sum(int a, int b){ return a+b; } public static double sum(int a, double b){ return a+b; } public static double sum(double b, int a){ return a+b; } public static float sum(float a,float b,float c){ return a+b+c; } public static void main(String[] args) { int a1=Calculate.sum(1,2); double a2=Calculate.sum(1,2.0); double a3=Calculate.sum(1.0,2); float a4=Calculate.sum(1.5f,2.5f,3.5f); System.out.println(a1); System.out.println(a2); System.out.println(a3); System.out.println(a4); } }