超级菜鸟问: 把一个方法赋值给一个变量是什么意思?

安庆老吴 2016-11-08 10:11:52
以下是 JAVA 官方英文教程里的例子,粗体的那一行是什么意思,为什么把一个方法赋值给一个变量?

class Whatever {
public static varType myVar = initializeClassVariable();

private static varType initializeClassVariable() {

// initialization code goes here
}
}
...全文
356 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
yetian_lin 2016-11-11
  • 打赏
  • 举报
回复
你自己看一下方法中的英语的意思 这只是一个例子,中间那块让你写初始化用的方法的代码。 因为很多变量初始化的时候是根据实际情况赋予不同的值。所以才会用方法计算然后给一个返回值初始化... 至于静态的问题随便查一下就知道了。
NewMoons 2016-11-09
  • 打赏
  • 举报
回复
确实是超级菜鸟,不过支持你这种不耻下问的精神。 楼上已经给出正确答案了,现在剩下的就是你自己敲代码去验证了,不要只是纸上谈兵。
nikyotensai 2016-11-09
  • 打赏
  • 举报
回复
楼上说得对
安庆老吴 2016-11-09
  • 打赏
  • 举报
回复
感谢各位,但是那一段教程的全文是这样的。 Static Initialization Blocks A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Here is an example: static { // whatever code is needed for initialization goes here } A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code. There is an alternative to static blocks — you can write a private static method: class Whatever { public static varType myVar = initializeClassVariable(); private static varType initializeClassVariable() { // initialization code goes here } } The advantage of private static methods is that they can be reused later if you need to reinitialize the class variable. 说是把变量初始化的过程给弄成静态化,第二红色语段当中的方法就是初始化类中的成员变量的,为什么要有返回值啊。把几个变量初始化了,要返回啥值呢?
  • 打赏
  • 举报
回复
楼上们说的对
___d 2016-11-09
  • 打赏
  • 举报
回复
方法肯定是有返回值的,不然就一定不能这样去赋值
Be_nurturing 2016-11-09
  • 打赏
  • 举报
回复
后面的那个方法执行完后,会有一个varType类型的值返回,然后就给了了myVar变量。
小灯光环 2016-11-08
  • 打赏
  • 举报
回复
就是把这个方法的返回值赋给myVar 变量~ 这是初始化的一种形式~ 作用类似于静态块~

62,628

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧