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

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.

主站蜘蛛池模板: 武鸣县| 武平县| 五莲县| 涞水县| 南涧| 元氏县| 政和县| 称多县| 大同市| 孟州市| 双柏县| 山西省| 高邮市| 西安市| 长岭县| 普定县| 晋州市| 桦川县| 鲜城| 通榆县| 锡林郭勒盟| 通许县| 繁昌县| 永安市| 杭锦后旗| 石景山区| 孟连| 珠海市| 涡阳县| 洮南市| 昌吉市| 商洛市| 上蔡县| 黔江区| 永兴县| 丹阳市| 平谷区| 腾冲县| 桐柏县| 拜城县| 新干县|