1. 程式人生 > >java中介面類似c++中純虛擬函式

java中介面類似c++中純虛擬函式


interface CalInterface
{
    final float PI=3.14159f;//定義用於表示圓周率的常量PI
    float getArea(float r);//定義一個用於計算面積的方法getArea()
    float getCircumference(float r);//定義一個用於計算周長的方法getCircumference()
}


public class Demo implements CalInterface   
{  
    
    public float getArea(float r)   
    {  
        float area=PI*r*r;//計算圓面積並賦值給變數area  
        return area;//返回計算後的圓面積  
    }  
    
    
    public float getCircumference(float r)   
    {  
        float circumference=2*PI*r;      //計算圓周長並賦值給變數circumference  
        return circumference;           //返回計算後的圓周長  
    }  
    
    
    public static void main(String[] args)   
    {  
        Demo c = new Demo();  
        float f = c.getArea(2.0f);  
        System.out.println(Float.toString(f));  
    }  


      在類的繼承中,只能做單重繼承,而實現介面時,一次則可以實現多個介面,每個介面間使用逗號“,”分隔。這時就可能出現常量或方法名衝突的情況,解決該問題時,如果常量衝突,則需要明確指定常量的介面,這可以通過“介面名.常量”實現。如果出現方法衝突時,則只要實現一個方法就可以了。下面通過一個具體的例項詳細介紹以上問題的解決方法。