我的读书笔记之-----类的继承与多态性以及方法重载

在java中,类的继承需要用到关键字extends

如下面的代码:

package javaapplication9;
/**
 *
 * @author Lamorh
 */
class Person
{
    int age;
    String name;
    int avoirdupois;
    public void eat()
    {
        System.out.println("People eat");
    }
    public void sleep()
    {
        System.out.println("People sleep");
    }
}


public class JavaApplication9  extends Person{
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        JavaApplication9 text=new JavaApplication9();
        text.eat();
        text.sleep();
    }
}

运行结果:


子类可以继承父类的东西,

但子类有时也需要增加一些自己的特性,

而这个就靠关键字:super

如:

package javaapplication9;


/**
 *
 * @author Lamorh
 */
class Person
{
    int age;
    String name;
    int avoirdupois;
    public void eat()
    {
        System.out.println("People eat");
    }
    public void sleep()
    {
        System.out.println("People sleep");
    }
}


public class JavaApplication9  extends Person{
    /**
     * @param args the command line arguments
     */
    public void eat()
    {
        super.eat();
        System.out.println("Worker eat");
    }
    public static void main(String[] args) {
        // TODO code application logic here
        JavaApplication9 text=new JavaApplication9();
        text.eat();
        text.sleep();
    }
}

运行结果:


当然,有时候子类也需要改变父类的一些特性,于是就需要

进行函数的修改,于是只需要重写该函数即可。



函数的重载:

package calculate;


/**
 *
 * @author Lamorh
 */
public class Calculate {


    /**
     * @param args the command line arguments
     */
    final float PI=3.1415926f;
    public float GetArea(float r)
    {
        return PI*r*r;
    }
    public float GetArea(float l,float w)
    {
        return l*w;
    }
    public static void main(String[] args) {
        // TODO code application logic here
        Calculate cal=new Calculate();
        float l=10.0f;
        float w=20.0f;
        float areaRectangle=cal.GetArea(l, w);
        System.out.println("长为:"+l+" 宽为:"+w+"的矩形的面积为:"+areaRectangle);
        float r=8.0f;
        float areaCire=cal.GetArea(r);
        System.out.println("半径为:"+r+" 的圆的面积为:"+areaCire);
    }
}

运行结果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值