Scala中調用Java方法注意點


1. 定義兩個存在父子關系的Java類 

/**
 * @Auther: 123
 * @Date: 2021/6/11 11:00
 * @Description: 測試scala調用java類中繼承的父類方法
 */
public class JSON {
    public static String parser(String str){
        return "static JSON.parser: "+str;
    }
    public  String format(String str){
        return "JSON.format: "+str;
    }
}
/**
 * @Auther: 123
 * @Date: 2021/6/11 11:02
 * @Description:
 */
public class JSONObject extends JSON{
    public static String childParser(String str){
        return "static JSONObject.childParser: "+str;
    }

    public  String childFormat(String str){
        return "JSONObject.childFormat: "+str;
    }
   // 不同點:java中調用靜態方法可以使用對象或者類
    public static void main(String[] args) {
        JSONObject object = new JSONObject();
        System.out.println(object.childFormat("sssss"));
        System.out.println(object.childParser("sssss"));
     System.out.println(JSONObject.childParser("sssss"));
} }

 

2. Scala中使用Java方法

 
/**
* 測試調用java代碼
*/
def testJavaCode = {
var mainDo = new MainC()
mainDo.doWork(" my work ")

val str = " zhangsanlisiwangwuzholiu "
val json = new JSON()
val jsonObject = new JSONObject()

// 嘗試調用JSONObject中繼承JSON的方法
println(""+jsonObject.format(str))
println(""+JSONObject.parser(str)) // 編譯不過

// 嘗試調用JSON的方法
println(""+json.format(str))
println(""+JSON.parser(str))

// 嘗試調用JSONObject中自己的方法
println(""+jsonObject.childFormat(str))
println(""+JSONObject.childParser(str))

/**
* 總結:
* 1. scala中調用java中靜態方法只能使用當前類不能使用對象
* 2. java中靜態方法盡管是public在scala中都無法使用子類調用
* 3. java中非靜態子類可繼承方法在scala中可以使用子類對象調用
*/
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM