近来跟着网上的python教程内容看不懂了,完全没接触过,先看看java缓两天。
abstract(n:抽象)
关键字abstract关键字修饰的类称为抽象类
abstract class A{
}
用关键字abstract修饰的方法称为抽象方法。
对于抽象方法,只允许声明,不允许实现(没有方法体),而且不允许finnal和abstract修饰同一方法或类,也不允许static修饰abstr方法,即abstract方法必须是实列方法。
abstra类不能用new 运算符创建对象
abstract类的子类必需重写abstra类中的方法
abstra类的对象作为上转型对象
abstract class GirlFriend {
abstract void speak();
abstract void cooking();
}
class ChinaGirlFriend extends GirlFriend {
void speak() {
System.out.println("你好");
}
void cooking() {
System.out.println("水煮鱼");
}
}
class AmericanGirlFriend extends GirlFriend {
void speak() {
System.out.println("Hello!");
}
void cooking() {
System.out.println("Roast beef");
}
}
class Boy {
GirlFriend friend;
void SetGirFriend(GirlFriend f) {
friend = f;
}
void showGirlFriend() {
friend.speak();
friend.cooking();
}
}
public class Test {
public static void main(String[] args) {
GirlFriend girl = new ChinaGirlFriend(); //girl is Upper Transition Object
Boy boy = new Boy();
boy.SetGirFriend(girl);
boy.showGirlFriend();
girl = new AmericanGirlFriend();
boy.SetGirFriend(girl);
boy.showGirlFriend();
}
}
面向抽象编程
在程序设计中我们经常会使用abstra类,因为它只关心操作,而不在意具体实现细节。
所谓的面向抽象编程,是指设计某种重要的类时,不让该类面向具体的类,而是面向抽象类。
import java.awt.*;
public class Test {
public static void main(String[] args) {
double a,b;
Pillar pillar;
Geometry bottom=null;
pillar=new Pillar(bottom,100);
System.out.println("体积"+pillar.getVolume());
bottom=new Rectangle(12,22);
pillar=new Pillar(bottom,58);
System.out.println("体积"+pillar.getVolume());
bottom=new Circle(10);
pillar=new Pillar(bottom,58);
System.out.println("体积"+pillar.getVolume());
}
}
abstract class Geometry {
abstract double getArea();
}
class Pillar {
Geometry bottom; //bottom is a variable by the abstract class geometry
double height;
Pillar(Geometry bottom, double height) {
this.bottom = bottom;
this.height = height;
}
public double getVolume() {
if (bottom == null) {
System.out.println("没有底,无法计算面积!");
return -1;
}
return bottom.getArea() * height; //Bottom can call the getArea method that the subclass overrides
}
}
class Circle extends Geometry {
double r;
Circle(double r) {
this.r = r;
}
public double getArea() {
return (3.14 * 3.14 * r);
}
}
class Rectangle extends Geometry{
double a, b;
Rectangle(double a, double b) {
this.a = a;
this.b = b;
}
double getArea() {
return a * b;
}
}
这样设计就不需要修改Pillar类的任何代码,就可以使用Pilloar创建出来的 对象。