java中子类_java中子类继承

本文介绍了Java中子类继承父类的概念,展示了如何重写父类的方法。子类可以调用并修改父类的非构造器方法。示例代码演示了如何在子类中调用父类被覆盖的方法以及如何访问继承的静态和非静态成员。
摘要由CSDN通过智能技术生成

[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);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值