/*
*
* 方法重写:
* 1.方法名必须相同
* 2.参数列表必须相同
* 3.返回类型相同或是其子类
* 4.不能缩小访问权限
*
* 方法重载和方法重写的区别
* overload方法重载,同一个类中,方法名相同,参数列表不同
* override方法重写,父子类中,方法名、参数、返回值相同
*/
/*
* 动物类
*/
public class Animal
{
// 属性
String name;
String sex;
int health;
// 方法
public void cry(){
System.out.println("俺是动物,俺在叫。。。。。");
}
public Animal getAnimal(){
System.out.println("返回一只动物");
return new Animal();
}
}
/*
* 猫咪类,继承自Animal
*/
public class Cat extends Animal
{
public void cry(){
System.out.println("喵喵。。。");
}
}
/*
* 狗狗类,继承自Animal
*
*/
public class Dog extends Animal
{
// 重写父类中的cry方法
public void cry()
{
System.out.println("旺旺。。。");
}
// 重写父类中的getAnimal方法
public Dog getAnimal()
{
System.out.println("返回一条狗");
return new Dog();
}
}
/*
* 测试类
*/
public class Test
{
public static void main(String[] args)
{
// 创建子类Dog的对象
Dog dog = new Dog();
dog.cry(); // 子类重写父类的方法后,调用的是子类重写后的方法
dog.getAnimal();
}
}
/*
* 计算类
*
* 重载sum方法
* 同一个类中,多个方法,其名称相同,但参数不同(个数、类型、位置)
* 与方法的返回值和修饰符无关
*/
public class Calc
{
// 计算两个整数的和
public int sum(int num1, int num2)
{
return num1 + num2;// 返回两数之和
}
// 计算两个double类型数值的和
public double sum(double num1, double num2)
{
return num1 + num2;
}
// 计算两个float类型数值的和
public float sum(float num1, float num2)
{
return num1 + num2;
}
}
public class Test
{
public static void main(String[] args)
{
Calc c = new Calc();// 创建对象
float sum = c.sum(13,12f);
System.out.println("两数之和:" + sum);
}
}
原文:http://blog.csdn.net/wangzi11322/article/details/44565967