Reading notes of "Head First Java" of abstract classes and interfaces

Abstract class

①abstract parent class can be declared as abstract methods, no content can also be subclasses override.
②abstract to classes and methods at the same time declared
③ abstract method does not execute any statements
④ can not instantiate an abstract class, but you can instantiate the abstract class subclass
⑤ abstract class only for inherited
⑥ abstract class can force subclasses to implement of abstract methods defined
⑦ abstract methods defined in fact equivalent to the "standard"

pubulic abstract class Shape{//定义一个抽象类shape
	pubulic abstract double are();//抽象方法没有执行语句(面积)
}
pubulic class Rect extends Shape{//继承于shape的rect类(长方形)
	private final double weigth;
	private final double length;
	public Rect(double weigth,double length){
		this.weigth=weigth;
		this.length=length;
	}
	pubulic	double are(){
		return weigth*length;
	}
}
pubulic class Circle extends Shape{//圆形
	private final double R;
	public Circle(double R){
		this.R=R;
	}
	pubulic double are(){
		return Math.PI*R*R;
	}
}
public class Main{
	public static void main(String [] args){
	Shape s1=new Rect(200,100);//向上转型
	Shape s2=new Circle(2);//注意方法签名要一样
	System.out.println(s1.are());
	System.out.println(s2.are());
	}
}
Shape中没有给出求面积的具体执行语句,而是在子类中分别定义的
从Main函数可以看出我们只关心shape类当中有求面积的方法
我们并不想知道是怎么求的面积
	

For the essence of abstract programming

① upper code only defines a "specification"
② subclasses may not require compiler normally
③ abstract method implementation process is implemented by different subclasses, the caller does not care

抽象方法定义了子类必须实现的接口规范
定义了抽象方法的类就是抽象类
从抽象类继承的子类必须实现抽象方法
如果不实现抽象方法该子类仍然是一个抽象类
如果一个抽象类没有任何执行语句,那么所有的方法都是抽象方法就可以把该抽象类改变为接口(interface)

Java interface is built purely abstract interface

Interface implemented using the implements ①
② In one subclass can implement multiple interface
distinction term
interfaces ①Java interface interface especially by the definition, only the signature method
② Programming Interface refers to interface specifications, such as method signatures, data formats, network protocols and other
interface inheritable equivalent expansion interface

public interface Shape{
	double are;//pubulic abustract就可以不写了
}
public interface Shape,person,student{//实现多个接口
             // 抽象方法
}

interface

① pure abstract interface defines specifications
② class can implement multiple interfaces
③ is a data type interfaces for upward transition and the downward transition
④ not define the interface instance fields
⑤ interface methods defined in the default

public interface Shape{//因为是接口,所有的抽象方法都得被用到
	double are();
	default double zhouchang(){//有些地方用不到我们就把他改成default方法就不会报错了
		return 0;//返回值0;
	}
}
Published 48 original articles · won praise 5 · Views 1378

Guess you like

Origin blog.csdn.net/LebronGod/article/details/104579016