Husker14
Husker14

Reputation: 586

Is it possible to extend a class from another class that only has one constructor with package visibility?

I would like to be able to do the following, keeping in mind that class A and B are in two different packages and I can't modify class A or put class B in the same package of class A:

class A{
    A(){
        //stuff
    }
}

class B extends A{
    public B(){
        //stuff
    }
}

this code gives "Cannot find simbol: constructor A". Is there any way around that?

Upvotes: 1

Views: 3002

Answers (4)

Oriely
Oriely

Reputation: 143

In case you can't change class A, you can try to add a new class to the package where A is and extend it to use A, then use B to extend it from the new class.

Upvotes: 3

gpeche
gpeche

Reputation: 22504

You say you cannot put class B in the same package as A. But could you have some helper class H in that package? I mean:

package a;

class A { ... }

package a;

public class Helper extends A {
    public Helper() { }
}     

package b;

import a.Helper;

class B extends Helper {
    B() { }
}

I guess you are dealing with sealed packages so this is not possible, but if it is not the case, then this solution should work.

Upvotes: 0

mcalex
mcalex

Reputation: 6778

The first thing a class does in its constructor is to call the constructor of its superclass. As class A doesn't have a public no-arg constructor, you cannot extend B the way you're trying.

If there is a public constructor that takes arguments, you are able to extend it, as long as you call super(arg1, ...); as the first call in your class' constructor:

public B()
{
    super(arg1, arg2, argN);
    // stuff
}

Upvotes: 2

PermGenError
PermGenError

Reputation: 46408

unless, you make Class A public, NO is the ANSWER, because your Class A has default scope which is only confined to the package level. to make it access outside your package mark it as public

Upvotes: 2

Related Questions