构造方法和方法重载的区别

构造方法三个条件: 
①、方法名和类名相同 
②、在方法名前面没有返回值类型的声明 
③、在方法中不能使用return语句java

方法重载三个条件: 函数

①、方法名相同,参数类型不一样
②、参数个数不一样,参数顺序不一样
③、重载跟方法的返回值类型无关,只跟方法的参数有关this

方法重写条件:code

①、重写方法必须和被重写的方法具备相同的方法名称,参数列表和返回值字符串

②、重写方法不能使用比被重写方法更严格的访问权限class

③、父类中的私有方法不能被重写,在子类重写的方法中继续调用父类被重写的方法能够经过调用super.函数名获取。权限

 

package package1;

public class Demo6 {
	public static void main(String[] args) {
		Printer aa=new Printer(1000);
		aa.print(100);
		aa.print("hahahahah");
		aa.print("hahahaha", 88);
	}
}
class Printer{
	private String brand="联想";
	private double price;
	//构造方法
	public Printer(double price) {
		this.price=price;
	}
	public Printer(double price,String brand) {
		this.price=price;
		this.brand=brand;
	}
	//方法的重载
	public void print(String content) {
		System.out.println("字符串"+content);
	}
	public void print(int content) {
		System.out.println("整形"+content);
	}
	public void print(String str,int content) {
		System.out.println(str+"---"+content);
	}
	/*
	 * 错误的重载方式
	 * public int print(int content) {
		return content;
	}*/
	//重载跟方法的返回值类型无关,只跟方法的参数有关
	public int  print(int content,double d) {
		return content;
	}
}
相关文章
相关标签/搜索