Arpit
Arpit

Reputation: 394

Using main class inside the package in java

I am trying to to run the file Demo.java which is calling Protection class within the same package but it is giving error This is the main class.

package p1;
// Instantiate the various classes in p1.
class Demo {
  public static void main(String args[]) {
    Protection ob1 = new Protection();
    //Derived ob2 = new Derived();
    //SamePackage ob3 = new SamePackage();
  }
}

And this is the class that I want to use in the main class.

package p1;

public class Protection {

  public int n = 1;
  private int n_pri = 2;
  protected int n_pro = 3;
  public int n_pub = 4;

  public Protection() {
    System.out.println("base constructor");
    System.out.println("n = " + n);
    System.out.println("n_pri = " + n_pri);
    System.out.println("n_pro = " + n_pro);
    System.out.println("n_pub = " + n_pub);
  }
}

It is giving this error:

$ javac Demo.java
Demo.java:6: error: cannot find symbol
Protection ob1 = new Protection();
^
  symbol:   class Protection
  location: class Demo
Demo.java:6: error: cannot find symbol
Protection ob1 = new Protection();
                     ^
  symbol:   class Protection
  location: class Demo
2 errors
error: compilation failed

Upvotes: 0

Views: 2000

Answers (2)

layman1988
layman1988

Reputation: 1

You could try this:

  1. open cmd in p1, use javac .\Demo.java .\Protection.java; then you can see two .class files generated
  2. use cd .., then you can see your package p1
  3. use java p1.Demo then you can see the expected output

Upvotes: 0

Olivier Grégoire
Olivier Grégoire

Reputation: 35427

You should use javac, not java only

When you use the command java, you can execute a file, but only the classes in that file. Here you have several files, so you should compile them in order to use them.

Do the following:

$ mkdir p1
$ mv Demo.java Protection.java p1/
# edit p1/Demo.java to change `class Demo` to `public class Demo`
$ javac p1/*
$ java p1.Demo

This worked and resulted in the following:

base constructor
n = 1
n_pri = 2
n_pro = 3
n_pub = 4

Upvotes: 1

Related Questions