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

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.

主站蜘蛛池模板: 襄汾县| 贵阳市| 屏东县| 浪卡子县| 西宁市| 玛纳斯县| 天等县| 赤水市| 新巴尔虎右旗| 湛江市| 黄山市| 阿拉善盟| 区。| 赤壁市| 肥西县| 和田市| 长寿区| 靖江市| 达孜县| 图们市| 尼勒克县| 肇州县| 长葛市| 阳东县| 四子王旗| 开阳县| 历史| 永兴县| 攀枝花市| 伊金霍洛旗| 玛多县| 报价| 延吉市| 信宜市| 博罗县| 府谷县| 莎车县| 卓资县| 秦皇岛市| 思茅市| 定兴县|