0

I have 2 snippets:
in one it's all wrapped up in the main class and both methods and classes are declared static. In the second snippet the classes are outside the main class and only the methods are declared static. My questions are:

  • what is the right way to do things?
  • because if they are in main everything must be static while outside only the methods must be?
class main{  

     static class  numeri{
        int a;
        int b;
        static int result;
        
        static  void  sommaNumeri(int a, int b){
            System.out.println("contenuto della superclasse " + (a + b));
            result = ( a + b);
            System.out.println(result);
        }// end metodo sommaNumeri
    }//end class numeri

    static class  numeri2 extends numeri  {
        int c;
        int d;

        static  void  sommaNumeri2( int a, int b, int c ,int d){
            System.out.println("contenuto della sottoclasse " + (a + b + c + d));
        }// end metodo numeri2
    }// end class numeri2

    public static void main ( String args[]){
        numeri.sommaNumeri(3,5 );
        numeri2.sommaNumeri2(4, 6, 7, 9 );
        numeri2.sommaNumeri(8, 9 );
    }// end main method
}// end main class


class  numeri{
        int a;
        int b;
        static int result;
        
        static  void  sommaNumeri(int a, int b){
            System.out.println("contenuto della superclasse " + (a + b));
            result = ( a + b);
            System.out.println(result);
        }// end metodo sommaNumeri
    }//end class numeri

     class  numeri2 extends numeri  {
        int c;
        int d;

        static  void  sommaNumeri2( int a, int b, int c ,int d){
            System.out.println("contenuto della sottoclasse " + (a + b + c + d));

        }// end metodo numeri2
    }// end class numeri2


    class main{  

    public static void main ( String args[]){
        numeri.sommaNumeri(3,5 );

        numeri2.sommaNumeri2(4, 6, 7, 9 );

        numeri2.sommaNumeri(8, 9 );


    }// end main method
}// end main class
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Antonio
  • 13
  • 1
  • 1
    What is your code supposed to do? – khelwood Nov 30 '21 at 16:19
  • None of those code examples looks light. What is the purpose of non-static *fields* there? You are not using them, instead you are using method arguments with same names. Also generally we should *avoid* `static` fields (more info: [Why are static variables considered evil?](https://stackoverflow.com/q/7026507)). – Pshemo Nov 30 '21 at 16:22

5 Answers5

1

First: keep to the convention that class names start with a capital. Really helps me and others.

Inner classes should be made static. Example:

class Outer {

    private int answer = 42;
    private void r() { }

    static class StaticInner {

        void p() {
            // Cannot use <var>answer</var>.
        }
    }
    
    class EmbeddedInner {

        void q() {
            answer %= 13;
            Outer.this.answer += 39;
            Outer.this.r();
        }
    }
}

Outer o = new Outer();
StaticInner si = new StaticInner();
EmbeddedInner ei = o.new EmbeddedInner();

A non-static embedded class object has besides its this (EmbeddedInner.this) also one for its outer class (Outer.this).

This means sometimes it is usesfull to know its container object, and a non-static inner class automatically provides that. But if not needed, a static inner class spares an Outer.this. In fact serializing an inner object would always serialize the outer object.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
1

My question are: -what is the right way to do things? -because if they are in main everything must be static while outside only the methods must be?

There is no one right way to do things, but as your programs become more complicated you will find that you usually want to avoid static, non-final variables, and as a result, the scope for using static methods will decrease.

Note well that in your example code, the only method that must be static is main.main(). You choose to make the various sommaNummeri methods static, and therefore are able to invoke them as static methods. (Or maybe you decided to invoke them as static methods, and then found that the compiler required them to in fact be static for that to work.)

To bootstrap from the static context of a main() method to non-static context, you instantiate one or more objects and invoke instance methods on them. Example:

class Numeri {
    int result;
        
    void sommaNumeri(int a, int b) {
        System.out.println("contenuto della superclasse " + (a + b));
        result = ( a + b);
        System.out.println(result);
    }
}

class Numeri2 extends Numeri  {

    void sommaNumeri2(int a, int b, int c, int d) {
        System.out.println("contenuto della sottoclasse " + (a + b + c + d));
   }
}

class Main {  

    public static void main(String args[]) {
        Numeri2 num = new Numeri2();

        num.sommaNumeri(3, 5);
        num.sommaNumeri2(4, 6, 7, 9);
        num.sommaNumeri(8, 9);
    }
}

Note also that according to the usual Java coding conventions, class names should begin with an initial capital letter, as shown.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
1

Java is supposed to be object oriented. Nothing about static is object oriented. New programmers use static as a crutch to avoid learning OO. As a learner, try to avoid static wherever possible.

Guidelines for using the static keyword for new programmers:

  1. you have to use it for the entry point (main method) because no objects are created yet.

  2. do not nest classes inside each other. There are very few cases that actually helps, mostly you just cause yourself confusion. That way you never need to write "static class"

  3. use static final for constant fields only. Do not put anything in a static field that you need to change. Do not mess with complicated things like lazy singletons or holders, and don't use static fields to pass data between classes because you can't be bothered to give objects references to each other.

  4. use static for methods where the value returned is the result of manipulating the inputs, that have no dependencies and no side effects (for instance, writing to a database is a side effect).

  5. don't use static for anything that needs to be overridden. Static doesn't do polymorphism.

  6. if this is any other case not allowed above, don't use static for it.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
0

In the 1st snippet, you defined what's called an inner class. As the class is static and its methods are static, you can access it with main.numeri and methods with main.numeri.sommaNumeri

In the 2nd snippet, you didn't define inner class. You can access it with numeri.sommaNumeri.

I suppose that's you're a Java debutant, so you probably need to follow Java basic best practices and define public classes and methods in their own separated files. Both of them must be public to be accessed from your file where main is defined. For example:

Numeri.java

public class Numeri {
    public void sommaNumeri(int a, int b) {
        System.out.println("contenuto della sottoclasse " + (a + b + c + d));
    }
}

Then you can access it like this:

Main.java

import my.package.Numeri;

public class Main {
    public static void main (String args[]){
         Numeri.sommaNumeri(3, 5);
    }
}

Important point: class names must start with uppercase. You can hurt Java people deeply by not following this naming convention!

Benjamin Caure
  • 2,090
  • 20
  • 27
0

TLDR: 'Static' keyword applied to a method just means that you can call this method without first creating an instance of the class. Since both snippet 1 and snippet 2 declare the methods as static (static void sommaNumeri(int a, int b) and static void sommaNumeri2( int a, int b, int c ,int d)), there is no real difference here.

Detailed: In object oriented programming (OOP), objects contain data and methods to operate on that data. One principal of OOP is encapsulation, which refers to accessing data of an object, and it aims to help prevent incorrect usage of the object by making the fields private and defining getters and setters.

In your example, you have 2 classes, both of which only have one method, and since that method is static, you can call methods sommaNumeri1 and sommaNumeri2 without creating instances of numeri and numeri2. Recall that a class is a blueprint for an object, so we could try instantiating the objects:

class Num { 
    private int a;
    private int b;

    public num(int a, int b) {
        this.a = a;
        this.b = b;
    }

    public void print() {
        System.out.println("sum: " + (a+b));
    }
}
...
// somewhere in a main class
public static void main(String[] args) {
    Num num1 = new Num(4,5);
    Num num2 = new Num(7,8);
    num1.print() // this should print 'sum: 9'
    num2.print() // this should print 'sum: 15'
}

However, if you had a static method, you wouldn't need to create any objects (as you can see with your code snippets 1 and 2 don't ever call new keyword!).

Now you have also static nested classes in snippet 1. This means that the classes numeri and numeri2 are nested but cant access other members of the outer class class main. If you were to remove the static keyword from the class definitions of numeri and numeri2 in snippet 1, the objects would be able to access other members of the outer class main.

I think here the answer really depends on what you want to happen. Since both classes only have a static method each, you could get rid of numeri and numeri2 and keep the methods sommaNumeri and sommaNumeri2 inside main class. However, nesting classes "is a way of logically grouping classes that are only used in one place", so if you really feel the need to have the classes nested you could leave them there.

If you do leave the classes in main, you may want to think about whether you want your classes to be static or not, and whether those methods need to be static (the question being, do you want to access those methods without creating objects first? In other words, do you need to access data of an object inside the method?).

Hope this helps! Please let me know if something was unclear :D

(N.B: what really helps me thinking about java objects is mathematical objects. When I came to this realisation I really re-thought a lot about OOP! Java objects are just like vectors. Vector [1,2,3] contains information, represents x=1, y=2, z=3. You can perform operations ON the vector, like multiplying it by 2: 2*[1,2,3] = [2,4,6]. To do an operation ON a vector, you need A vector. In java, if an method is NOT static, thats the same there, you need an OBJECT to call that method on, just as you need a vector to do scalar multiplication on.)

ferrouskid
  • 466
  • 2
  • 7
  • thanks, so i use static method if i don`t want create object but if i create an object and make an instance of object isn`t necessary to use static method. it's right? – Antonio Nov 30 '21 at 21:11
  • Nearly there :) If you want to have a method that needs only the parameters you pass into it, you can make it `static`. To me, `static` just means "the same for everyone", so a `static` method ONLY depends on the parameters you pass in. But if you want to use data from the object, you *don't* use static. For example, if you had a "Person" object with date of birth, and you wanted to calculate people's age. You could have a method "public Date calculateAge(){ return date.now() - this.dateOfBirth() }" - since we are using data from the person object, we DONT use static. – ferrouskid Dec 01 '21 at 12:10
  • Object oriented programming is really useful when you have loads of objects (object = instance of class) and you want to do operations ON those objects (so *not* static methods). Like if you have an online shop, you can have many `Customer` objects, and you could find out how much *each* customer spends, so you could create (*not static*) method to find out `customer1.getMoneySpent()`, or `customer2.getMoneySpent()` - thats the beauty of OOP, but theres other ways of coding! Like "Functional Programming" (I think it really helps understanding the differences, so you can appreciate WHY use OOP) – ferrouskid Dec 01 '21 at 12:17