Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to create a Java class everytime?

Tags:

java

oop

I am starting to learn the Java programming language and I am a little confused.

I would like to create a simple program like adding two numbers or calculate the sum of n numbers. I can do this in C or Python easily, but in Java, I have to create a class for my program and then create a main class and call my program from it.

I use both Netbeans and IntelliJ.

Can I just create the program directly the way I do it in other languages? I mean is the concept of a class necessary in Java?

like image 865
Kira Avatar asked Apr 28 '15 18:04

Kira


People also ask

Is it necessary to create a class in Java?

The creation of classes in Java is necessary because they give your program structure, and reduce the amount of code that is present in your program. Instead of creating a new state and behavior for each similar object in a program, you can simply call the class that has the template for the creation of that object.

When should I create a class in Java?

A common reason to define a new class is to encapsulate related data in an object that can be treated as a single unit. That way, we can use objects as parameters and return values, rather than passing and returning multiple values.

Does every Java program need a class?

Yes. In Java you always need one class with the function main to have the JRE run it.

What is the purpose of creating a class?

In object-oriented programming, a class is a blueprint for creating objects (a particular data structure), providing initial values for state (member variables or attributes), and implementations of behavior (member functions or methods).


1 Answers

Can I just create the program directly the way I do it in other languages?

No.

I mean is the concept of class necessary in Java?

Yes. Every method, field etc is always in a class (or interface). Yes, that's an overhead for tiny programs - but for larger programs, the impact is pretty tiny.

As ever, use the right tool for the job - if you want a script of a few lines, use a scripting language. If you want more structure and organization, then you should expect a bit of "ceremony" to go with that.

like image 132
Jon Skeet Avatar answered Oct 01 '22 03:10

Jon Skeet