pemistahl
pemistahl

Reputation: 9584

How to restrict public method access to superclass?

In my Scala project, I have the following class hierarchy:

class A {

  def methodA = ...
  ... other methods here ...
}

class B extends A {

  ... other methods here ...
}

In my class design, it makes perfect sense to make B a subclass of A. The only problem is that methodA is only applicable to class A but not to class B. Unfortunately, I cannot set methodA to private because it needs to be callable from any instance of class A.

Do I have to rethink my class design or is it possible to restrict the access to public method methodA to class A?

Upvotes: 1

Views: 82

Answers (2)

Yuriy
Yuriy

Reputation: 2769

One of possible way below:

class A protected() {
  //.... methods ....
}

trait AExt extends A {
  def foo(s : String) = println(s)
}

object A {
  def apply() : A with AExt = new A with AExt
}

class B extends A {
  //.... methods ....
} 

val a = A()
a.foo("hello")

val b = new B()
//  b.foo("hello") // no 'foo' method

Upvotes: 0

Alexey Romanov
Alexey Romanov

Reputation: 170745

In my class design, it makes perfect sense to make B a subclass of A. The only problem is that methodA is only applicable to class A but not to class B.

These statements can't be true at the same time.

Unfortunately, I cannot set methodA to private because it needs to be callable from any instance of class A.

Every instance of B is an instance of A (that's just what "subclass" means). So if the method isn't callable from an instance of B, it isn't "callable from any instance of class A".

Upvotes: 3

Related Questions