03课堂问题整理

03课堂问题整理

1、分析以下代码,方法square的定义写了static,如果去掉static,就会报错,为什么呢?

public class SquareIntTest {

public static void main(String[] args) {

int result;

 

for (int x = 1; x <= 10; x++) {

result = square(x);

System.out.println("The square of " + x + " is " + result + " ");

}

}

// 自定义求平方数的静态方法

public static int square(int y) {

return y * y;

}

}

分析解答:static,是静态的,属于公共的,不需要实例化;如果不带static,,就必须实例化类,再调用该方法。解决方法如下:

public class SquareIntTest {

public static void main(String[] args) {

int result;

SquareIntTest t=new SquareIntTest();

for (int x = 1; x <= 10; x++)

{

result = t.square(x);

System.out.println("The square of " + x + " is " + result + " ");

}

}

// 自定义求平方数的方法

public  int square(int y) {

return y * y;

}

}

2、方法重载。观察以下程序。

public class MethodOverload {

 

public static void main(String[] args) {

System.out.println("The square of integer 7 is " + square(7));

System.out.println(" The square of double 7.5 is " + square(7.5));

}

 

public static int square(int x) {

return x * x;

}

 

public static double square(double y) {

return y * y;

}

}

满足以下条件的两个或多个方法构成重载关系:

1)方法名相同;

2)参数类型不同,参数个数不同,或者是参数类型的顺序不同。

原文地址:https://www.cnblogs.com/hjy415/p/5964884.html