java程序,抽象类实现,求具体代码

java程序,抽象类实现,求具体代码,第1张

package test

/**

*

* @author JinnL

*父类抽象

*/

public abstract class Car {

//转弯

abstract void turn()

//启动

abstract void start()

void what(){

System.out.println("this is "+this.getClass().getSimpleName())

}

public static void main(String[] args) {

/**

* 方法入口

*/

Car[] cars ={new Bicycle(),new Automobile(),new GasAutomobile(),new DieselAutomobile()}

for (Car car : cars) {

car.start()

}

}

}

class Bicycle extends Car{

@Override

void turn() {

System.out.println("this is "+this.getClass().getSimpleName())

}

@Override

void start() {

System.out.println("this is "+this.getClass().getSimpleName())

}

void what(){

}

}

class Automobile extends Car{

@Override

void turn() {

System.out.println("this is "+this.getClass().getSimpleName())

}

@Override

void start() {

System.out.println("this is "+this.getClass().getSimpleName())

}

}

class GasAutomobile extends Automobile{

//重写start turn

@Override

void turn() {

System.out.println("this is "+this.getClass().getSimpleName())

}

@Override

void start() {

System.out.println("this is "+this.getClass().getSimpleName())

}

}

class DieselAutomobile extends Automobile{

@Override

void start() {

System.out.println("this is "+this.getClass().getSimpleName())

}

void what(){

System.out.println("this is "+this.getClass().getSimpleName())

}

}

数据抽象就是针对对象的属性,比如建立一个鸟这样的类,鸟会有以下特征,两个翅膀,两支脚,有羽毛等等特性,写成类都是鸟的属性

过程抽象就是针对对象的行为特征,比如鸟会飞,会跳等等,这些方面的就会抽象为方法,即过程,写成类都是鸟的方法

//抽象的形状类

abstract class Shape{

abstract double getArea()//抽象的求面积方法

}

//矩形类

class Rectangle extends Shape{

protected double width

protected double height

public Rectangle(double width, double height){

this.width = width

this.height = height

}

@Override

double getArea() {//实现父类的方法

return this.width * this.height

}

}

//椭圆类

class Ellipse extends Shape{

protected double a

protected double b

public Ellipse(double a, double b){

this.a = a

this.b = b

}

@Override

double getArea() {

return Math.PI * this.a * this.b

}

}

public class TestAbstract {

public static void main(String[] args) {

Shape s

s = new Rectangle(3, 4)

System.out.println("矩形的面积 : " + s.getArea())

s = new Ellipse(4, 3)

System.out.println("椭圆的面积 : " + s.getArea())

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/12025563.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-20
下一篇 2023-05-20

发表评论

登录后才能评论

评论列表(0条)

保存