栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java

方法覆盖的条件

条件一:两个类必须要有继承关系条件二:重写之后的方法要和之前的方法具有:
相同的返回值类型
相同的方法名
相同的形式参数列表条件三:访问权限不能更低条件四:重写之后的方法不能比之前的抛出更多的异常 可以更少 注意事项:

方法覆盖只是针对于方法 和属性无关
私有方法无法覆盖
构造方法不能被继承 所有也不能被覆盖
方法覆盖只是针对于实例方法 静态方法没有意义

public class OverrideTest01
{
	public static void main(String[] args)
	{}
}
class Animal
{
	//  移动
	public void move()
	{
		System.out.println("动物在移动");
	}
}
// 子类
class Bird extends Animal
{
	// 这里的业务需求是要输出鸟儿在飞翔的
	// 但继承之后 它只能输出 动物在移动
}

需要用到方法覆盖来解决这个问题

public class OverrideTest01
{
	public static void main(String[] args)
	{
		Bird s=new Bird();
		s.move();

	}
}
class Animal
{
	//  移动
	public void move()
	{
		System.out.println("动物在移动");
	}
}
// 子类
class Bird extends Animal
{
	// 这里的业务需求是要输出鸟儿在飞翔的
	// 但继承之后 它只能输出 动物在移动

	public void move()
	{
		System.out.println("鸟儿在飞翔");
	}
	// 其实很简单 就是将方法再重新抄一遍 把你所需要的需求修改一下就行
}
关于继承后在创建的对象里面直接传值的问题
public class OverrideTest02
{
	public static void main(String[] args)
	{
		//创建对象
		ChinaPeople s=new ChinaPeople();
		// 注意:你还是不能在s中直接传值给ChinaPeople
		// 因为在ChinaPeople里它没有将构造方法继承过去 你在s里面传值 它根本接收不到
		s.setName("张三");
		s.speak();
		AmericanPeople c=new AmericanPeople();
		c.setName("李四");
		c.speak();

	}
}
class People
{
	private String name;
	public People()
	{}
	public People(String name)
	{
		this.name=name;
	}
	public void setName(String name)
	{
		this.name=name;
	}
	public String getName()
	{
		return name;
	}

	public void speak()
	{
		System.out.println(name+",,,");
	}

}

// 子类
class ChinaPeople extends People
{
	// 方法覆盖
	public void speak()
	{
		System.out.println(getName()+"正在说汉语");
	}
}
class AmericanPeople extends People
{
	public void speak()
	{
		System.out.println(getName()+"正在说英语");
	}
}
关于java内置库中objuct 的用法
public class OverrideTest03
{
	public static void main(String[] args)
	{
		MyDate s1=new MyDate(1977,10,11);
		System.out.println(s1.toString());
		System.out.println(s1);// 这里不加方法名  系统也会自动给它加上toString()
	}
}

class MyDate  // 默认是继承objuct
{
	private int year;
	private int month;
	private int day;

	public MyDate()
	{}
	public MyDate(int year,int month,int day)
	{
		this.year=year;
		this.month=month;
		this.day=day;
	}

	public void setYear(int year)
	{
		this.year=year;
	}
	public int getYear()
	{
		return year;
	}
	public void setMonth(int month)
	{
		this.month=month;
	}
	public int getMonth()
	{
		return month;
	}
	public void setDay(int day)
	{
		this.day=day;
	}
	public int getDay()
	{
		return day;
	}


	// 对MyDate的默认继承Objuct进行方法覆盖
	public String toString()
	{
		return year+"年"+month+"月"+day+"日";
	}
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/721778.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号