Question

I am new to java and i am writing this code in notepad which is giving me errors.In netbeans although package is already defined.How to do this in notepad?

package A;
class A {
    private String name;
    protected String company="oracle";  
    A(String name) {
        this.name = name;
        System.out.println(name);
    }
}

public class B extends A {
    // A public class constant
    public final static String st = "Public access modifiers";

    B(String name) {
        super(name);
    }
    void getCompany()
    {
        System.out.println(company);
    }

}

package B;//getting class interface or enum expected 
public class Application {
    public static void main(String[] args) {
        System.out.println(st);
        B b=new B("Java");
        b.getCompany();
    }
}
Was it helpful?

Solution

You can not put different packages into the same source file... You have to create the appropriate folder structure, and separate Java source files for the sources in each package...

Also, to be able to reference classes from other packages, you have to import them appropriately, and make sure they are actually on the classpath both for compiling and running too......

Recommended reading

OTHER TIPS

package B;//getting class interface or enum expected 

remove this line Package declaration should be the first line of the source file.

You can not write 2 or more different packages with in the same source

The package statement should be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file.

The PackageOrTypeName must be the canonical name (§6.7) of a package, a class type, an interface type, an enum type, or an annotation type.

That is what it is telling, and remove multiple declarations of package

And you should import the class B, When they both belongs to different packages.

import packagePath.B;

If a single-type-import declaration imports a type whose simple name is n, and the compilation unit also declares a top level type (§7.6) whose simple name is n, a compile-time error occurs.

Language Specification

Side note: Do not write multiple classes in a single java file. Later It's very hard to maintain the code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top