java中采用关键字extends继承一个类
子类
测试
子类可以使用父类中的方法(除了private方法之外)
子类可以覆盖(override)父类中的方法(private因为invisible不能覆盖,final也不能覆盖)
可以将子类对象赋值给自身或者直系长辈(即父类,父类的父类。。),而不能反过来将父类对象赋值给子类。当将子类对象赋值给父类变量的时候,不可以使用子类专有的方法。
父类
public class Father {
/**
* @param args
*/
void method1()
{
System.out.println("F.method1");
}
void method2()
{
System.out.println("F.method2");
}
private void method4() //invisible in 子类
{
System.out.println("F.method4");
}
final void method5() //can not override
{
System.out.println("F.method5");
}
}
子类
public class Son extends Father{
void method2()
{
System.out.println("S.method2");
}
void method3()
{
System.out.println("S.method3");
}
}
测试
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Father tf = new Father();
System.out.println("Father tf = new Father(),tf.m1,tf.m2");
tf.method1();
tf.method2();
Father tf2 = new Son();
System.out.println("Father tf2 = new Son(),tf2.m1,tf2.m2");
tf2.method1();
tf2.method2();//使用了子类方法,不能使用父类中没有,子类中定义的方法
Son ts = new Son(); //cannot convert from Father to Son
System.out.println("Son ts = new Son(),ts3.m1,ts3.m2");
ts.method1();
ts.method2();
ts.method3();
}