Reputation: 1065
In Java
, the abstract class's static member will be inherited all through its subclasses.
like
abstract class TopThing{
public TopThing next;
public TopThing(TopThing tt){
this.next = tt
}
private static HashTable<String, TopThing> someTable = new HashTable<String,TopThing>();
protected void add(String name) {
someTable.put(name, this);
public static Parent forName(String name) {
return someTable.get(name) ;
}
}
class SomeSpecific extends TopThing {
public final String name;
public SomeSpecific (String name, TopThing tt) {
super(tt);
this.name = name;
this.add(name);
}
This is I am first time writing in Scala, the only way I know to achieve the above is using companion object, but it seems does not work for this case
add
method, how can the subclass's instance referred and be inserted into the table? (the question is also about this
in add
method)Upvotes: 1
Views: 125
Reputation: 3649
For question 1: you can use private[namespace]
For question 2: no, but you can use import
class Xxx {
import Xxx._
...
}
For question 3: I don't known how to answer it.
For question 4:
trait TopThing {
val someTable: HashTable[String, TopThing]
}
class Xxx extend TopThing {
val someTable = Xxx.someTable
}
Upvotes: 0
Reputation: 170859
Yes, it can.
Yes, you reference it as TopThing.someTable
(or just someTable
after import TopThing._
).
Same as in Java: this
. So
abstract class TopThing(val next: TopThing) {
protected def add(name: String) {
TopThing.someTable += (name -> this)
}
}
object TopThing {
private val someTable = collection.mutable.Map[String,TopThing]()
def forName(name: String) = someTable.get(name)
}
class SomeSpecific(val name: String, next: TopThing) extends TopThing(next) {
this.add(name)
}
Upvotes: 6