Plz explain line no 6 nd 7 . Why we need to create object of binary class using object of main class?
Doubt about the code
Static fields and methods are connected to the class itself and not its instances. If you have a class A
, a ‘normal’ method b
, and a static method c
, and you make an instance a
of your class A
, the calls to A.c()
and a.b()
are valid. Method c()
has no idea which instance is connected, so it cannot use non-static fields.
The solution for you is that you either make your fields static or your methods non-static. You main could look like this then:
public class Main{
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
Main m = new Main();
BinaryTree tree = new BinaryTree(sc);
tree.leftView();
}
class BinaryTree {
// can now access non-static fields
}
}
or you could just say
public class Main{
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
//Main m = new Main();
BinaryTree tree = new BinaryTree(sc);
tree.leftView();
}
static class BinaryTree {
///code
}
}