JMV12
JMV12

Reputation: 1035

Package Inside Package Java

I've been given the instructions: Write an interface called Playable, with a method void play();. Let this interface be placed in a package called music.Write a class called Veena which implements Playable interface. Let this class be placed in a package music.string.

I have created the interface and packaged it below:

package music;

interface Playable {
    public void play();
}

I then created the next class below:

package music.string;
import music.Playable;

public class Veena implements Playable {
    public void play() { System.out.println("Veena plays"); }
}

I've played around with this and so far, I either don't get to name the package it's in to "music.string" or I receive an error since Playable is not public and cannot be used outside the interface. How would I import and implement Playable in my class Veena while also packaging Veena in "music.string"?

Upvotes: 0

Views: 2764

Answers (2)

Kushagra Misra
Kushagra Misra

Reputation: 481

you cannot access interface from different package in case it is not defined public. If you want to keep your interface default you have to move your classes to same package, but as you have an requirement to keep your interface in separate package(which is a good design also) make your interface public.

package music;

public interface Playable {
   void play();
}   

Upvotes: 0

davidxxx
davidxxx

Reputation: 131326

Make the interface public :

public interface Playable {
     void play();
}

A package-private class/interface may only be referenced by classes/interfaces belonging to the exact same package.

Upvotes: 1

Related Questions