[root@server254 java]# vim Ostrich.java //注意文件名必须是这个,因为下面代码中只有Ostrich是public修饰符。我们要明白public的含义
class Bird { public void Fly() { System.out.println("I am bird I can fly"); } } public class Ostrich extends Bird { public void Fly() { System.out.println("I am bird But I can not fly"); } public static void main(String[] args) { Ostrich f = new Ostrich();//死 f.Fly(); } }
子类繼承了父类,子类就拥有了父类的所有的方法,可以直接调用,可以修改,虽然,构造器也是一种特殊的方法,但是,子类不能繼承到父类的构造器,这是java的规定。
上面這個例子就是子類繼父類,而且還可以重寫父類的方法!只要方法名字一定一樣!
class Bird { public void Fly() { System.out.println("I am bird I can fly"); } } public class Ostrich extends Bird { public void Fly() { System.out.println("I am bird But I can not fly"); } public void callOverrideMethod() { super.fly();//使用super限定,去调用Bird类中被覆盖的方法,这样Ostrih类就可以去访问被自己覆盖的父类的方法 } public static void main(String[] args) { Ostrich f = new Ostrich(); f.Fly(); } }
当然我们怎么在子类中繼承父类的成员呢?就像Feild一样,可是成员又包括类成员和对成员,就像类Feild和对象Feild,我们该怎么在子类中调用这些从父类中繼承的成员呢?
正確:
子类繼承了父类后,想调用父类,调用父类中的类Feild话需要使用 父类名.成员名
class Bird { static String name; //这是一个类Feild,子类繼承了它 public void Fly() { System.out.println("I am bird I can fly"); } } public class Ostrich extends Bird { public void Fly() { System.out.println("I am bird But I can not fly"); } public static void main(String[] args) { Ostrich f = new Ostrich(); f.Fly(); Bird.name = "maque";//子类调用时必须使用Bird不能使用super,因为这是个static修饰的,属于类本身 System.out.println(Bird.name); } }
非static修飾的
class Bird { String name; public void Fly() { System.out.println("I am bird I can fly"); } } public class Ostrich extends Bird { public void Fly() { System.out.println("I am bird But I can not fly"); } public static void main(String[] args) { Ostrich f = new Ostrich(); f.Fly(); super.name = "maque"; System.out.println(Bird.name); } }
本文出自 “8176010” 博客,谢绝转载!
java中子類繼承,布布扣,bubuko.com
原文地址:http://8186010.blog.51cto.com/8176010/1405677