官术网_书友最值得收藏!

Importance of classes and objects in Java

Objects are instances or references of a class. So we can call the methods and variables present in this class with the help of their objects. We cannot call methods and objects directly, we can only use them with the help of their objects. So first, we need to create objects for the class, and then we can call the method inside the main class.

Let's take a look at the previous example to explain this:

package coreJavaTraining;

public class Firstclass {

public void getData()
{
System.out.println(" I am in method");
}
public static void main(String[] args)
{
System.out.println("hi");
System.out.println("hello world");
}
}

Since the main block is already in the class, why do we need to create an object again for this class and call it?

The answer is that there is no way that the main block will come to know about the method outside it until and unless we create an object to call the method. There is an exception for that, which is the static variable, saying that the method is static. So, in general, accessing other methods is only possible with objects.

主站蜘蛛池模板: 辽阳县| 紫阳县| 平乐县| 柏乡县| 五河县| 温州市| 元氏县| 商水县| 雅江县| 阜新| 搜索| 扶风县| 灵石县| 高碑店市| 天台县| 吴江市| 黑水县| 兴和县| 洛隆县| 家居| 铁岭县| 黎城县| 寿宁县| 含山县| 田东县| 宁晋县| 册亨县| 略阳县| 黄龙县| 禄劝| 鄯善县| 威信县| 普格县| 无锡市| 永定县| 翁牛特旗| 健康| 莱西市| 凤翔县| 故城县| 合川市|