(overheard at the office, and we thought others will benefit)
Suppose I have a base class in a library, which provides some basic features, but which is intended to be derived from by the library user.
For example, I have an abstract Greeting class. Subclasses represent specific types of greetings, like HighFiveGreeting or HugGreeting or whatever. Greeting provides some utility functions for subclasses, like sendGreeting()
. I don't want users of these classes to call sendGreeting()
.
Is that possible? Is there a better idiom in Dart for this kind of thing?
library greeting; abstract class Greeting { void sendGreeting(GreetingEvent event) { ... } }
library custom_greeting; import 'greeting.dart'; class HugGreeting extends Greeting { // code here uses sendGreeting() }
library main; import 'custom_greeting.dart'; var hug = new HugGreeting(); hug.sendGreeting(...); // should not compile
The only way to emulate interface in Dart is to create abstract class. That means that in Dart abstract class is mixed with interface.
@protected is an annotation (and not a language keyword) provide from package:meta and that is used by dartanalyzer .
You have to either make the property public, declare the two classes in the same library, or not access the property from the subclass. There are no other options. That won't help you read the private variable later, it's still only the superclass, and other code in the same library, which can access the variable.
Dart Private Variables In dart, you can declare a variable name with an underscore(_) as a private variable. Private variables are accessed inside the same class, not outside the classes or files. Declared a private variable ie added an underscore before a variable(_) in a class.
Like stated here, now there is the @protected
annotation in the meta package
I would love to know the reasons why to omit the public|private|protected keywords from the language BTW... :'(
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With