zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Scala调用Java静态成员及静态方法注意点——只能通过当前类名调用而不能借助子类调用父类静态成员/方法

JAVA方法静态scala 通过 调用 不能 当前
2023-09-14 09:02:02 时间

只能通过当前类名NioUtil调用静态成员

package com.zxl.scala

import cn.hutool.core.io.{FileUtil, IoUtil, NioUtil}
import java.io.BufferedInputStream
import java.io.BufferedOutputStream

object HuToolsDemo {
  def main(args: Array[String]): Unit = {
    val in: BufferedInputStream = FileUtil.getInputStream("D:/Develop/kubectl/test.txt")
    val out: BufferedOutputStream = FileUtil.getOutputStream("D:/Develop/kubectl/test2.txt")
    //编译不通过,不能通过子类调用父类的静态成员 public class IoUtil extends NioUtil
    //val copySize: Long = IoUtil.copy(in, out, IoUtil.DEFAULT_BUFFER_SIZE)
    //只能调用当前类的静态成员,并且只能通过类名调用
    val copySize: Long = IoUtil.copy(in, out, NioUtil.DEFAULT_BUFFER_SIZE)
  }
}

进一步佐证

父类

package com.zxl.extend;
/**
 * 父类
 * */
public class JSON {
    public static String parser(String str) {
        return "static JSON.parser: " + str;
    }

    public String format(String str) {
        return "JSON.format: " + str;
    }
}

子类

package com.zxl.extend;
/**
 * 子类
 * */
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"));
    }
}

scala调用java静态方法

package com.zxl.extend
/**
 * 总结:
 *    1. scala中调用java中静态方法只能使用当前类名,不能使用对象
 *    2. java中静态方法尽管是public在scala中都无法使用子类调用
 *    3. java中非静态子类继承父类的方法,在scala中可以使用子类对象调用
 */
object TestJavaCode {

  def main(args: Array[String]): Unit = {
    testJavaCode()
  }

  def testJavaCode(): Unit ={
    val str: String = "some contents"
    val json: JSON = new JSON()
    val jo: JSONObject = new JSONObject()

    // 尝试调用JSONObject中继承JSON的方法
    println(jo.format(str))
    //子类实例调用父类的static方法,编译都通不过
    //println(jo.parser(str))

    // 尝试调用JSON的方法
    println(json.format(str))
    //调用类的static方法,不能通过对象来调,编译都通不过
    //println(json.parser(str))
    //调用类的static方法,只能通过类名来调
    println(JSON.parser(str))

    // 尝试调用JSONObject中自己的方法
    println(jo.childFormat(str))
    //调用类的static方法,只能通过类名来调
    println(JSONObject.childParser(str))
  }
}

总结

  1. scala中调用java中静态方法只能使用当前类名,不能使用对象
  2. java中静态方法尽管是public在scala中都无法使用子类调用
  3. java中非静态子类继承父类的方法,在scala中可以使用子类对象调用