一、成员变量的隐藏
在编写子类时,我们仍然可以声明成员变量,如果所声明的成员变量的名字和父类继承来的成员变量的名字相同(类型可以不同),那么子类就会隐藏所继承的成员变量
特点:
1、子类对象以及子类自己定义的方法操作与父类同名的成员变量是指子类重新声明的这个成员变量
2、子类继承的方法所操作的成员变量一定是被子类继承或隐藏的成员变量
3、子类仍然可以调用从父类继承的方法操作子类隐藏的成员变量
注:
子类继承的方法只能操作子类继承和隐藏的成员变量
子类新定义的方法可以操作子类继承和子类新声明的成员变量,无法操作子类隐藏的成员变量(需使用super关键字)
class Goods
{
public double weight;
public void oldsetweight(double w)
{
weight = w;
System.out.println("double型的weight = " + weight);
}
public double oldgetprice()
{
double price = weight * 10;
return price;
}
}
class CheapGoods extends Goods
{
public int weight;
public void newsetweight(int w)
{
weight = w;
System.out.println("int型的weight = " + weight);
}
public double newgetprice()
{
double price = weight * 10;
return price;
}
}
public class Example_3
{
public static void main(String args[])
{
CheapGoods one = new CheapGoods();
//one.weight = 198.23; 非法,因为子类对象的weight已经是int型
one.newsetwight(198);
System.out.println("对象one的weight的值是: " + one.weight);
}
}
二、方法重写(方法覆盖)
子类通过重写可以隐藏已继承的方法
1、重写规则:
方法的名字,参数个数,参数的类型与父类的方法完全相同
2、重写的目的:
子类通过方法的重写可以隐藏继承的方法,子类通过方法的重写可以把父类的状态和行为改变为自身的状态和行为
如果父类的一个方法可以被子类继承,那么子类就有权重写这个方法,一旦重写了这个方法,就隐藏了继承的这个方法。对象调用时一定是调用重写后的。
重写的方法既可以操作继承的成员变量,调用继承的方法,也可以操作子类新声明的成员变量、调用新定义的其他方法,无法操作被子类隐藏的成员变量和方法
如果子类想使用被隐藏的方法或成员变量,必须使用关键字super
class University
{
void enterRule(double math,double english,double chinese)
{
double total = math + english + chinese;
if(total >= 180)
System.out.println("达到分数线");
else
System.out.println("未达到分数线");
}
}
class ImportantUniversity extends University
{
void enterRule(double math,double english,double chinese)
{
double total = math + english + chinese;
if(total >= 250)
System.out.println("达到分数线");
else
System.out.println("未达到分数线");
}
}
public class Example_4
{
public static void main(String args[])
{
double math = 62,english = 76,chinese = 55;
ImportantUniversity univer = new ImportantUniversity();
//调用重写后的方法
univer.enterRule(math,english,chinese);
math = 91;
english = 87;
chinese = 88;
univer.enterRule(math,english,chinese);
}
}
注:
重写父类的方法时,不允许降低方法的访问权限,但可以提高访问权限
class A
{
protected float f(float x,float y)
{
return x + y;
}
}
class B extends A
{
float f(float x, float y) //非法,降低了访问权限
{
return x - y;
}
}