Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible for an interface to be accessible only in the same package and child packages?

Tags:

java

interface

Is it possible for an interface to be accessible only in the same package and child packages?

I have defined an interface with default modifier:

package com.mycompany.myapp.dao;

import java.io.Serializable;

interface BaseDao<T, Id extends Serializable> {
    public void create(T t);    
    public T readById(Id id);   
    public void update(T t);    
    public void delete(T t);
}

Now I have a child package where I want to define a class which implements BaseDao. So I wrote this code:

package com.mycompany.myapp.dao.jpa;

import java.io.Serializable;

public class BaseDaoJpa<T, Id extends Serializable> implements BaseDao<T, Id> {
...
}

But I get this error:

BaseDao cannot be resolved to a type

So is this a restriction from Java for an interface or am I doing it wrong way?

Thanks

like image 957
srh Avatar asked Jun 19 '15 14:06

srh


2 Answers

In Java there is no such thing as a "child package". Don't get fooled by the dots. com.mycompany.myapp.dao and com.mycompany.myapp.dao.jpa are two separate packages which have no relation to each other.

So to answer your question: no, it is not possible to make an interface visible only to child packages. You can make your interface public, but then it will be visible to all other packages.

like image 148
Hoopje Avatar answered Sep 21 '22 11:09

Hoopje


Have a look on Java Acess Modifiers: https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

In the table you can see that default or No modifier is limited to acess only by the same class or other classes in the same package. As i understand you want it to be visible to other packages as well but not to the world, and for that you need to use protected modifier, but it is impossible since it is not aplicable so going back to your question no you cant :- (

like image 34
fill͡pant͡ Avatar answered Sep 18 '22 11:09

fill͡pant͡