04-23.eri-test Java主要方法:为什么有那么多单词?

\n

public static void main(String[] args){
\n// code
\n}

\n\n

ugh

\n\n

"Seriously? I have to type this every time i write a program? That is a lot and I miss JavaScript! \xf0\x9f\x98\xad" These were always my thoughts when I was in college just starting with Java after learning JavaScript for a bit.

\n\n

What we see above is the main method in Java. Let\'s break it down and talk about each word in this line of code.

\n\n

Public
\nPublic in Java is an access modifier. Access modifiers specify the accessibility or scope of a method, constructor, or a class. There are four access modifiers:

\n\n
  1. \n
  2. Private: the access level of this modifier is only within the class and cannot be accessed from outside of the class. \n
  3. Public: the access level of this modifier is everywhere and can be accessed within the class, outside the class, within the package and outside the package.\n
  4. Protected: the access level of this modifier is within the package and outside the package through child classes, without which it cannot be accessed from outside. \n
  5. Default: the access level of this modifier is only within the package, and cannot be accessed from outside the package. \n
\n\n

The main method has to be public because we want access to it.

\n\n

Static
\nIn Java, a static member of a class is a member that isn\'t associated with an instance of a class. This member belongs to the class itself and can be accessed without first creating a class instance. A method that is declared with the static keyword is associated with the class itself, and therefore we don\'t have to create an object from a class before using static methods defined by the class.

\n\n

If the main method is not static, JVM wouldn\'t be able to call it because there is no class object present. That\'s why the main method must be static so that JVM can call the main method which is not associated with an instance of a class.

\n\n

Void
\nThis one is simple. The keyword void is used at method declaration to indicate that the method should not have a return value, and this is why main method is void

\n\n

Main
\nMain is just a name for the method, and when we run a Java program, it looks for the name.

\n\n

Below is a simple program that calculates the Fibonacci of n recursively and prints out the result.

\n\n\n
\n \n
\n\n\n\n
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值