Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why all the java code is packed in Classes?

Tags:

java

class

I have started learning Java and picked up some books and collected materials online too. I have programmed using C++. What I do not understand is that ,even the main method is packed inside a Class in Java. Why do we have everything packed inside some class in Java ? Why it does not have independent functions ?

like image 360
shimna Avatar asked Dec 06 '10 08:12

shimna


People also ask

Why is everything inside a class in Java?

In Java, everything extends into an Object class. It means the coding is mostly wrapped in Java objects. The Java language assumes that you want to do only object-oriented programming. You cannot code anything in Java without declaring classes and objects.

Why is Java code written in class?

So because there's nothing but classes in Java (except the few Java primitive types, like int, float, ...) we have to define the main method, the starting point for a java application, inside a class. The main method is a normal static method that behaves just like any other static method.

Does all Java code have to be in a class?

Every Java program requires the presence of at least one class.

Does every Java program contain at least one class?

classes - A class is a blueprint for building objects in Java. Every Java program has at least one class.


1 Answers

This is the main concept of object oriented programming languages: everything is an object which is an instance of a class.

So because there's nothing but classes in Java (except the few Java primitive types, like int, float, ...) we have to define the main method, the starting point for a java application, inside a class.


The main method is a normal static method that behaves just like any other static method. Only that the virtual machine uses this one method (only) to start the main thread of the application.

Basically, it works like this:

  1. You start the application with java MyClass
  2. The JVM loads this class ("classloading")
  3. The JVM starts a new thread (the main thread)
  4. The JVM invokes the method with the signature public static void main(String[])

That's it (in brief).

like image 189
Andreas Dolk Avatar answered Sep 21 '22 23:09

Andreas Dolk