在java中,从静态方法调用非静态方法的最佳方法是什么?
我知道关于这个话题有很多问题。 我有两个过程调用arrPrint方法 第一程序:在java中,从静态方法调用非静态方法的最佳方法是什么?,java,static,Java,Static,我知道关于这个话题有很多问题。 我有两个过程调用arrPrint方法 第一程序: public class Test { public static void main(String args[]) { int[] arr = new int[5]; arr = new int[] { 1, 2, 3, 4, 5 }; Test test = new Test(); test.arrPrint(arr); } public void arrPrint(i
public class Test {
public static void main(String args[]) {
int[] arr = new int[5];
arr = new int[] { 1, 2, 3, 4, 5 };
Test test = new Test();
test.arrPrint(arr);
}
public void arrPrint(int[] arr) {
for (int i = 0; i < arr.length; i++)
System.out.println(arr[i]);
}
}
公共类测试{
公共静态void main(字符串参数[]){
int[]arr=新的int[5];
arr=newint[]{1,2,3,4,5};
测试=新测试();
测试。arr打印(arr);
}
公共无效arrPrint(int[]arr){
对于(int i=0;i
第二程序:
public class Test {
public static void main(String args[]) {
int[] arr = new int[5];
arr = new int[] { 1, 2, 3, 4, 5 };
arrPrint(arr);
}
public static void arrPrint(int[] arr) {
for (int i = 0; i < arr.length; i++)
System.out.println(arr[i]);
}
}
公共类测试{
公共静态void main(字符串参数[]){
int[]arr=新的int[5];
arr=newint[]{1,2,3,4,5};
arr打印(arr);
}
公共静态无效arrPrint(int[]arr){
对于(int i=0;i
哪个过程最好?为什么?实例方法在类的实例上运行,所以要执行实例方法,需要一个类的实例。因此,如果要从静态方法中调用实例方法,则需要对实例进行一些访问,可以是全局变量,也可以是作为参数传递的。否则,将出现编译错误。“实例方法”表示需要在类的实例上执行该方法。对象的要点是实例可以有自己的专用数据,实例方法会作用于这些数据,因此尝试在没有对象实例的情况下调用实例方法是没有意义的。如果您将示例改写为:
public class Test {
int[] arr = new int[] {1,2,3,4,5};
public static void main(String args[]) {
Test test = new Test();
test.arrPrint();
}
public void arrPrint() {
for (int i = 0; i < arr.length; i++)
System.out.println(arr[i]);
}
}
公共类测试{
int[]arr=新的int[]{1,2,3,4,5};
公共静态void main(字符串参数[]){
测试=新测试();
test.arrPrint();
}
公共印刷品(){
对于(int i=0;i
这样就简单了一点。Test的实例有自己的数据,实例方法可以访问并使用这些数据
看看像String或ArrayList这样的JDK类,看看它们是如何设计的。它们封装数据并允许通过实例方法访问数据
另一方面,静态方法看不到实例数据,因为它们不属于对象实例。如果实例方法不涉及任何实例数据,一些静态分析工具(如sonarqube)会建议将实例方法更改为静态方法。由于您的方法对传入的数据进行操作,并且不需要创建对象将其作为实例方法调用,因此最好是静态方法 如果要在另一个类中使用方法
arrPrint
,则使用第二个过程
public class A{
public int[] intArray;
public A(int[] intArray) {
this.intArray = intArray;
}
public int[] getIntArray() {
return intArray;
}
}
public class Pourtest {
public static void main(String args[]) {
int[] arr = new int[5];
arr = new int[] { 1, 2, 3, 4, 5 };
A a = new A(arr);
arrPrint(a.getIntArray());
}
public static void arrPrint(int[] arr) {
for (int i = 0; i < arr.length; i++)System.out.println(arr[i]);
}
}
公共A类{
公共int[]内部阵列;
公共A(整数[]整数){
this.intArray=intArray;
}
public int[]getIntArray(){
返回阵列;
}
}
公共级Pourtest{
公共静态void main(字符串参数[]){
int[]arr=新的int[5];
arr=newint[]{1,2,3,4,5};
A=新的A(arr);
arrPrint(a.getIntArray());
}
公共静态无效arrPrint(int[]arr){
对于(int i=0;i
为什么需要很多方法来调用实例方法?问哪一个更好?:)