1.一个子类不必非要使用继承下来的属性与方法,一个子类是可以选择覆盖已有的属性和方法,或添加新的属性和方法。
2.成员变量的继承与隐藏。
public:若其父类的成员变量声明为public类型,无论是不是在同一个包里,子类都能继承其父类的该成员。
private:若其父类的成员变量声明为private类型,任何子类都不能继承该成员。
默认(不写)成员:若其父类的成员变量声明为默认(不写)类型,包外的子类不能继承该成员变量。
protected:若其父类的成员变量声明为protected类型,若访问改变量的类位于包外,只有继承才能访问。
public class test{
public String str="父类的成员变量";
}
public class testnew extends test{
public void getShow(){
System.out.println(this.str );
}
}
public class main {
public static void main(String args[]){
testnew t = new testnew();
t.getShow();
}
}
成员变量的隐藏:子类中成员变量与父类的成员变量一样时,调用该成员变量时,被调的是子类的,父类的被隐藏了, 但是若用super.str时,还是引用的是父类的成员变量。
3 对象引用的使用
对象引用的强制类型转换。
public class test{
String member=" 我是父类成员变量";
}
public class testnew extends test{
String member = "我是子类的成员变量,父类也有";
}
public class main{
public static void main(String args[]){
test t = new testnew();
System.out.println("显示的是父类中的"+t.member) ;
System.out.println("显示的是子类的"+((testnew)t).member) ;
} //此时对象t 的调用的只是 父类中的变量,子类中的调用不了
}
方法的继承与重写
1 方法的继承规则:方法也是一种成员,因此继承规则与成员变量的继承规则是完全一样的。
public class test {
public void show(){
System.out.println("父类中的");
}
}
public class testnew extends test {
public void getShow(){
System.out.println("子类中的");
this.show();
}
}
public class main {
public static void main(String args[]){
testnew t = new testnew();
t.show();
t.getShow();
}
}
返回类型的规则:
1,基本数据类型:被重写方法的返回若为基本类型,则重写方法的返回类型必须与之完全相同
任何其他类都不能继承用final修饰的类,即使该类的访问限为public类型,也不能继承。
被final修饰的方法,该方法在子类中将无法重写,只能继承
抽象方法的继承与实现:抽象类的第一个非抽象子类必须实现其父类所有的抽象方法,其中也包括父类继承的抽象方法
接口---灵活性的基石
1.接口声明中隐含了abstract,所以永远不能用final来修饰接口(abstract代表了抽象,final代表最终(很具体))
interface Flyer{}
interface JetFlyer extends Flyer{}
2.接口中的成员变量都是隐含是"public static final"
3.接口中方法无法使用的修饰符:static(静态的,接口中的方法不能被重写),final()
抽象类与接口的不同之处 :抽象类更注重其是什么及其本质;而接口则不是,接口更注重具体有什么样的功能及其功能充当什么样的角色。