The Java abstract classes and abstract methods

The Java abstract classes and abstract methods

abstraction

Benpian key word is abstract , then what is the abstract? Baidu Encyclopedia tells us, is the abstract summarizes the specific issues of common terms, and other essential attribute, and will give up the individual aspects, attributes thought process. In Java, which is the common to each specific class method is extracted, placed in the base class and the base class does not need to know specific subclass this method is how to achieve this base class is called abstract category , which do not need to know the specific implementation of the method is an abstract method .

Abstract classes reflect the template pattern design, abstract class as a universal template multiple sub-classes, subclasses to extend, on the basis of the transformation of the abstract class, subclass but will generally retain the overall behavior of an abstract class.

Abstract classes and methods

Let's combine the code, a good wave analysis:

package com.my.pac18;

/**
 * @auther Summerday
 */
/*抽象是很有用的重构工具,能够让共有的方法沿着继承层次向上移动。*/
public abstract class Shape {
    //抽象类中的初始化块
    {
        System.out.println("Shape.instance initializer");
    }
    //抽象类中的实例变量
    private String color;
    //抽象类中可以有静态方法及属性。
    public static String name="形状";
    public static void output(){
        System.out.println("父类的static方法");
    }
    //计算周长,但是并不知道具体细节的抽象方法
    public abstract double calPerimeter();
    //返回形状的抽象方法

    //[修饰符] abstract 返回类型 方法名();
    public abstract String getType();
    //抽象类中的构造器,用于被继承
    public Shape() {
    }

    public Shape(String color) {
        System.out.println("Shape.Shape");
        this.color = color;
    }
    //抽象类中的普通实例方法
    public String getColor() {
        return color;
    }
}

class Circle extends Shape {
    private double radius;

    public Circle(String color, double radius) {
        super(color);
        this.radius = radius;
    }

    public void setRadius(double radius) {
        this.radius = radius;
    }

    @Override
    public double calPerimeter() {
        return 2 * Math.PI * radius;
    }

    @Override
    public String getType() {
        return getColor() + "圆形";
    }

    //如果从一个抽象类继承,并创建该新类的对象,就必须给基类的所有抽象方法提供定义。
    public static void main(String[] args) {
        Shape.output();
        //Shape是抽象类,不能创建Shape类的对象
        //但是可以让Shape类的引用变量指向其子类的对象
        Shape[] shapes = new Shape[]{new Circle("红色", 5), new Rectangle("绿色", 6, 6)};
        for (Shape p : shapes) {
            
            System.out.println(p.getType() + "的周长为" + p.calPerimeter());
        }

    }
}

class Rectangle extends Shape {
    
    private double length;
    private double width;

    public Rectangle() {
        System.out.println("父类的构造器不是为了创建对象,而是供给子类继承的");
    }

    public Rectangle(String color, double length, double width) {
        super(color);
        this.length = length;
        this.width = width;
    }

    public boolean isSquare() {
        return length == width;
    }

    public double calPerimeter() {
        return (length + width) * 2;
    }

    public String getType() {
        if (isSquare()) return getColor() + "正方形";
        return getColor() + "长方形";
    }
}

//测试结果
父类的static方法
Shape.instance initializer
Shape.Shape
Shape.instance initializer
Shape.Shape
红色圆形的周长为31.41592653589793
绿色正方形的周长为24.0

Follow the example above, we simply analyze, abstract classes and abstract methods in the end is what? You need to pay attention to what?

  • First, the definition of an abstract class : Shape class. It can be seen from the abstract class abstractmodified keywords.
//[修饰符] abstract class 类名
public abstract class Shape
  • Then Shape class defines two abstract methods (methods may be rewritten, not properties, abstract terms is directed to a method ): getType()and calPerimeter()can be seen when the body does not define an abstract method declarations method, because the base class and do not need to know the specific implementation is how, just know this method on it. You create an instance round, particularly circular perimeter count of how, to give the definition of the abstract class method circular.
//[修饰符] abstract 返回类型 方法名();
 public abstract double calPerimeter();
 public abstract String getType();

Precautions

  • If the child class inherits from the abstract superclass, then the subclass must override the abstract methods of the parent class, gives concrete realization of the method . Your dad said you would count the perimeter, you gotta tell you how to calculate the perimeter of it. However, if the sub-category method also override the parent class is also declared abstract so, then the parent class method is implemented in a subclass is also invalid. Like, you say you do not know how to calculate perimeter, Wang is really next door.
@Override
public double calPerimeter() {
    return 2 * Math.PI * radius;
}
@Override
public String getType() {
    return getColor() + "圆形";
}
  • An abstract class can not be instantiated , can not be used to call the new abstract class constructor creates an instance of an abstract class. You can imagine, since it is abstract, there is no much sense to create an instance of it, create an instance of a subclass of the concrete implementation to fix the problem.
  • An abstract class can be used as a data type, you can make reference variables pointing to it in the abstract class subclass object , well understood, is not the case, the benefits brought by the abstract reflected in what yet. Specific performance of the method invoked by the abstract class abstract class reference variable, can be performed according to the abstract method in accordance with the actual type of the referenced object dynamically at runtime binding.
  • An abstract class is a member to have a method (Method instance and class methods) to achieve specific, defined membership and attributes (instance attributes and class attributes).
//抽象类中的实例方法,子类继承使用。
public String getColor() {
        return color;
    }
//抽象类中可以有静态方法和属性,类名.方法(属性)调用。
public static String name="形状";
public static void output(){
    System.out.println("父类的static方法");
}
  • An abstract class may also have a builder, but only to supply a subclass inherits used as the above have said, you can not create abstract class instance object! ! ! (RECAP: a subclass can not inherit the parent class constructor, simply call the parent class constructor initialization code, inheritance and calls are not the same! )
//子类
public Shape() {
    }

public Shape(String color) {
    System.out.println("Shape.Shape");
    this.color = color;
}
  • Abstract class code blocks and also inner classes, on an inner class will then learn, the example is not temporarily.
 //抽象类中的初始化块
{
    System.out.println("Shape.instance initializer");
}
  • If there is a class abstract method, then this class must also be abstract . After all, you do not yet fully defined method, you create an instance and dim it. But you can not have an abstract class abstract method , but simply not to let anyone create an instance of an object.

  • Abstract subclass is the parent class may be specific . As, Object class is the superclass of all, it is concrete, Shape class that we defined is abstract.

  • Is an abstraction mechanism to achieve polymorphism, then do not have the polymorphism, we can not be called polymorphism. Such as private, static, final modified constructor method is a static binding, it does not have the polymorphism, not as an abstract modification.

This article is based on the following information as well as personal income test, for any errors or irregularities understanding, but also hope the comments section points out, thank you.

Guess you like

Origin www.cnblogs.com/summerday152/p/12081810.html