java方法的重载

                                                                                    java方法的重载

public class Person1 {
    private String name; //姓名
    private int age;      //年龄
    private String school;  //学校
    private String major; //班级
    //构造方法
    public Person1 (String n,int a,String s,String m)
    {
        this.name=n;
        this.age=a;
        this.school=s;
        this.major=m;
    }
    //三个参数
    public Person1 (String n,int a,String s )
    {
        this(n,a,s,null);
    }
    //两个参数
    public Person1 (String n,int a)
    {
        this(n,a,null,null);
    }
    //两个参数
    public Person1 (String a,String m)
    {  
        /*
        this.name=a;
        this.age=Integer.parseInt(null);
        this.school=null;
        this.major=m;
        */
        this(a,Integer.parseInt(null),null,m);
    
    }
    public static void main(String[]args)
    {
        Person1 a=new Person1("马云",18);
        System.out.println("姓名:"+a.name+" "+"年龄:"+a.age);
        
    }

}

注:相关知识点,方法构造,方法的重载。

1.方法的构造,在类中方法名必须和类名相同

2.方法的重载,必须满足方法名相同,不同的参数类型或参数个数。跟方法的返回值无关。

3. public Person1 (String n,int a)
    {
        this(n,a,null,null);
    }

括号中的代码也可以这样写

this.name=n;

this.age=a;

this.school=null;

this.major=null;

但要注意整形和字符串之间的转化。例如 this.age=Integer.parseInt(null);因为this.age是整形的右边的赋值必须整形的,而null是字符串类型的。所以要将null转化为整形的

this.age=Integer.parseInt(null);

编程是一门艺术,要爱就要深爱。
原文地址:https://www.cnblogs.com/pwhit/p/4953908.html