简体   繁体   中英

Error appears when i try to call a method of class B in class A without main method

class B {
    void view(){
        System.out.println("in class b");
    }
}

public class A {
    
    B obj = new B();
    obj.view();
    
}

   

in this code on the line obj.view there appears an error: syntax error on token view, identifier expected after this token

class B {
    void view(){
        System.out.println("in class b");
    }
}

public class A {
    {
    B obj = new B();
    obj.view();
    }
}

but when i put those line in a block like above no compile time error appears there but there appears a run time error;

Error: Main method not found in class A, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application

Does it mean that i cannot run code without main method? if i need a main method then why eclipse is not showing any error when i put it in a block

The first piece of code fails because you don't have the code in class a in an initializer block, method or a constructor. The second piece of code puts it in an instance initializer, that's why the error has gone away.

However since the A class is public and I assume you don't have any other public classes at this point you need an entrypoint for the application. That is why the main method is necessary otherwise the program has no way to know where to start the application. Therefore this will work

class B {
void view(){
    System.out.println("in class b");
    }
}

public class A {
    public static void main(String[] args) {
        B obj = new B();
        obj.view();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM