Java static or inheritance variable

UI UX :

Let's say I have 3 classes A, B, C, and my Main. B extends A. I want to use a scanner in all of them include my main. should I move scanner by inheritance or should I use static and declare my scanner in my main?

I tried to look here but did not get a clear answer which is better: Is there any way I can use a Scanner object in a different class?

public class Main {
    public static Scanner staticScanner = new Scanner (System.in);
public static void main(String[] args) {
    Scanner sc = new Scanner (System.in);
    A a = new A(sc);
    C c = new C();
    c.cDoSomething(sc);
    sc.close();
    }

public class A {
    private Scanner sc;
    public A (Scanner sc){
    this.sc = sc;
    }
    public void aDoSomething(){
         B b = new B();
         b.bDoSomething(sc);

    }

public class B extends A {
    public void bDoSomething(Scanner sc){

    }

public class C {
    public void cDoSomething(Scanner sc){

    }

Like I said above I would like to understand which method is better and is the correct one to use. staticScanner and call it by my main class or move my Scanner sc between classes as needed

Trevor Freeman :

I think the answer here can depend on some of the specifics of the underlying classes and situation, particularly in regards to how coupled the state of the scanner might be to the state of other variables in the classes and how many separate methods or invocations are required.

Generally, however, I personally prefer c.doSomething(sc); if there is no internal state being kept in class C between method invocations. I.e. we do not have c.doSomething1(sc) and c.doSomething2(sc) that need to be called in order against the same scanner due to internal state being modified in C.

The counter argument being if we are making what is effectively a wrapper (or some form of decorator) around the Scanner that it makes perfect sense to pass the scanner in to the class in the constructor and keep a reference to it. I.e. if we want to have something like:

MyReader reader = new MyReader(scanner);
MyObject myObject = reader.readNextMyObject();

However, I think it would be very confusing if we were reading from the same scanner via multiple wrappers interleaved in code:

// I think the below would be UGLY, at least imho.
MyReaderA readerA = new MyReaderA(scanner);
MyReaderB readerB = new MyReaderB(scanner);
MyObjectX obj1 = readerA.readMyObject();
MyObjectY obj2 = readerB.readMyObject();

I think that would be confusing that two different readers are operating on the same scanner and moving its index.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=125153&siteId=1