面向对象编程----方法的重载(包含构造方法)
重载(overload)
方法的重载是指一个类中可以定义有相同的名字,但参数不同的多个方法。调用时,会根据不同的参数表选择对应的方法。
两同三不同
--同一个类,同一个方法名。
--不同:参数列表不同(类型,个数,顺序不同)
只有返回值不同,不构成方法的重载.(
Int a (String:str()),
Void a(String i),
调用:a()
谁能告诉我是调那个方法?
)
只有形参的名称不同,不构成方法的重载
与普通方法一样,构造方法也可以重载
package cn.Test.oop;
/**
* 测试重载
* @author 神奇的梦
*
*两同三不同
--同一个类,同一个方法名。
--不同:参数列表不同(类型,个数,顺序不同)
*/
public class TestOverload {
// 这样不会有歧义,因为这里调用时用new TestOverload(),
int x,y;
public static void main(String[] args) {
// 构建一个MyMath对象
MyMath m = new MyMath();
// 给方法中局部变量加上实参
MyMath mx = new MyMath(1,6);
// 方法的重载是指一个类中可以定义有相同的名字,
// 但参数不同的多个方法。调用时,会根据不同的参数表选择对应的方法。
}
}
// DDK是Device Development Kit,设备开发包的意思。
// 如果你想开发一个设备驱动程序,如显卡驱动程序,就必须使用DDK。
//不要叫Math,不然就冲突了,会有歧义
//在公共类(public修饰的类)里面写了一个Math在调ddk里面的Math调起来就很麻烦了
//也可以调,指定包名 尽量别重
//MyMath可以干嘛呢!可以算数
class MyMath{
int a=22;
int b=99;
// 构造方法
public MyMath() {
System.out.print(this.a+"三"+this.b);
}
// 构造方法不能重载 不行 因为初始化时,分不清初始化a还是初始化b了
// public MyMath(int xx) {
// this.ba指的是class MyMath类里面的int b,
// 而赋值号后面的xx指的是构造方法形参里面的int xx
// this.b=xx;
// }
public MyMath(int xx,int yy) {
// this.a指的是class MyMath类里面的int a,
// 而赋值号后面的xx指的是构造方法形参(局部参数)里面的int xx
// this.b指的是class MyMath类里面的int b,
// 而赋值号后面的yy指的是构造方法形参(局部参数)里面的int yy
this.a=xx;
this.b=yy;
System.out.print(this.a+"三克油"+this.b);
}
// 在这里我们提供这几个方法
// 对两个数做加法
// public double add(int b,double a) {
// return a+b;
// }
/* 形参类型不匹配,报错,不构成重载
public int add(int c,double d) {
return (int)(a+b);
}
*/
// Type mismatch: cannot convert from double to int
// 类型不匹配: 无法从 double 转换为 int
// 遭遇类型提升问题double+int结果时double需强制转型
/*
public int add(int a,double b) {
return a+b;
}*/
/**/
// 返回值不同不构成重载
// 当实参传递为int类型时,new它会报错
// public double add(double b,double a) {
// return (int)(a+b);
// }
// 返回值不同不构成重载
// public double add(int b,double a) {
// return a+b;
// }
// 重载方式:顺序不同
public int add(int b,double a) {
return (int)(a+b);
}
// 重载方式:类型不同
public int add(double a,int b) {
return (int)(a+b);
}
// 重载方式:数量不同
public int add(int a,int b) {
return (int)(a+b);
}
public int add(int a,int b,int c) {
return a+b+c;
}
}
package cn.Test.oop;
class Studentr {
private String name ;
private int age;
public Studentr() {
System.out.println("这是默认的构造方法");
}
public Studentr(String name) {
this.name = name;
}
public Studentr(int age) {
this.age = age;
}
public Studentr(String name, int age) {
this.age = age;
this.name = name;
}
public void show() {
System.out.println("name: "+name+"----age: "+age);
}
}
class ConstructDemo {
public static void main(String[] args) {
//Student s = new Student();
//System.out.println(s);
Studentr s0 = new Studentr();
Studentr s1 = new Studentr("刘轲");
s1.show();
Studentr s2 = new Studentr(30);
s2.show();
Studentr s3 = new Studentr("刘轲",30);
s3.show();
}
}
本文来自博客园,作者:神奇的梦,转载请注明原文链接:https://www.cnblogs.com/fantasticDream/p/16297486.html
浙公网安备 33010602011771号