博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
03课堂问题整理
阅读量:4536 次
发布时间:2019-06-08

本文共 1142 字,大约阅读时间需要 3 分钟。

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 + "\n");

}

}

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

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 + "\n");

}

}

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

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("\nThe 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

你可能感兴趣的文章
处理并解决mysql8.0 caching-sha2-password问题
查看>>
JavaScript 之 对象/JSON/数组
查看>>
判断delegate是否释放
查看>>
实验八
查看>>
时间日期函数
查看>>
java多线程的实现方法
查看>>
2016年终总结与来年计划
查看>>
10.9做的一个静态页面(巩固前面的内容)
查看>>
幸运男孩--点的hash
查看>>
大数的减法------神秘数
查看>>
洛谷P1658 购物
查看>>
Using Perl in Oracle 11gR2 Database
查看>>
Rabel 1.3.9 发布,让论坛回归交流本质
查看>>
Mac 安装brew和安装composer
查看>>
不用系统函数将字符串转换成整型【Java算法】
查看>>
Nginx限速遇到的问题
查看>>
判断当前主机是不是阿里云内网
查看>>
Java疯狂讲义(二)
查看>>
简简单单安装debian桌面工作环境
查看>>
ORACLE 11g EXPDP 的停止、启动和监控
查看>>