读书笔记(第二十一讲)abstract class

本文深入探讨了Java编程中的抽象类和抽象方法的概念,包括它们的特点、作用以及如何通过继承来实现抽象类中的抽象方法。通过实例展示了抽象类在面向对象编程中的实际应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这讲主要讲述了抽象类abstract class,抽象类的一个特点就是不能实例化。不能用new 关键字生成对象。否则编译的时候将出现错误,错误的提示也比较明显。
抽象类中也会有抽象方法abstract method在抽象方法中,特点是有声明,无实现。
抽象类与抽象方法之间的关系是:含有abstract method的class 要声明为abstract class,而abstract class中能有抽象方法与具体方法(有声明有实现)。抽象方法只能存在于抽象类中。
以上是抽象类的一些基本知识。

对于抽象类的继承,相于来说要复杂一些,子类若不是抽象类,则要实现抽象类中的所有抽象方法。
抽象类的好处可以用下面的实例说明:
public class Test2
{
public static void main(String[] args)
{
Shape shape=new Triangle(3,4);
System.out.println(shape.computeArea());

shape=new Rectangle(3,4);
System.out.println(rect.computeArea());



}
}
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;
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值