JavaSE 第二十一讲 多态详解续2 10.8

1.抽象类

public abstract class AbstarctTest
{

}

2.抽象方法

public class Test
{
    public static void main(String[] args)
    {
    
    }
}

abstract class T
{
    public abstract void method();//抽象方法,有声明无实现

    public void test()//抽象类中可包含具体方法
    {
        System.out.println("test");
    }
}

class R extends T  //继承父类(抽象类)所有的抽象方法;否则,子类也要声明成一个abstract class
{
    public void method()
    {
        System.out.println("method");
    }
}

3.抽象类作用

public class Test2
{
    public static void main(String[] args)
    {
        Shape shape = new Triangle(10,6);

        int area = shape.computeArea();

        System.out.println("triangle:" + area);

        shape = new Rectangle(10,10);

        area = shape.computeArea();

        System.out.println("rectangle:" + area);
    }
}

abstract class Shape
{
    public abstract int computeArea();//计算形状面积
}

class Triangle extends Shape
{
    int width;
    int height;

    public Triangle(int width, int height)
    {
        this.width = width;
        this.height = height;
    }

    public int computeArea()
    {
        return (width * height) / 2;
    }
    
}

class Rectangle extends Shape
{
    int width;
    int height;

    public Rectangle(int width, int height)
    {
        this.width = width;
        this.height = height;       
    }

    public int computeArea()
    {
        return width * height;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 32,968评论 18 399
  • 1 面向对象No6 面向对象 OO Object Oriented 编程时以对象为单元,封装数据和逻辑,以此提...
    征程_Journey阅读 4,902评论 0 2
  • 别等失去了朋友,才知道孤单; 别等失去了亲人,才知道温暖; 别等失去了爱人,才知道眷恋; 别等失去了缘分,才知道一...
    梦雅星辰阅读 1,738评论 0 0
  • 我15岁在纽约读高中的时候,因为心理压力非常大,再加上身边认识的所有的朋友(大概4,5个)非常“有默契”地一起...
    唐小新阅读 2,875评论 0 0

友情链接更多精彩内容