NeoZoom.lua
NeoZoom.lua

Reputation: 2901

Dart implementing a class would also inherit its fields?

I'm reading Language Tour of Dart https://dart.dev/guides/language/language-tour#implicit-interfaces:

class Person {

  final _name; /* this is the field of Person */

  ...
}


class Impostor implements Person {

  get _name => ''; /* so it's inherited? */

  String greet(String who) => 'Hi $who. Do you know who I am?';
}

In Java there are only constants(public static final thing) in interface. So it seems like Impostor also inherits the final _name from Person?

Upvotes: 1

Views: 631

Answers (2)

jamesdlin
jamesdlin

Reputation: 89946

So it seems like Impostor also inherits the final _name from Person?

It depends.

Privacy

If the implementing class is in the same library as the base (usually this means a different Dart file), then the base class's private interface will be visible to the implementing class and must be implemented as well.

If the implementing class is in a different library, then the base class's private interface will not be visible, and the implementing class is not expected to implement the private members.

Fields

(Visible) fields are part of the class's interface. An implementing class is required to implement that visible interface. If the base class has a public field, that really just means that its interface exposes public getter and setter methods with that name.

You can observe this yourself. If you put both of the following classes in the same Dart file:

class Base {
  Base() : _x = 42;

  final int _x;

  void _f() {}
}

class Derived implements Base {
}

You'll get an error:

Error: The non-abstract class 'Derived' is missing implementations for these members:
 - Base._f
 - Base._x
Try to either
 - provide an implementation,
 - inherit an implementation from a superclass or mixin,
 - mark the class as abstract, or
 - provide a 'noSuchMethod' implementation

But putting them in separate base.dart and derived.dart files (where derived.dart adds import 'base.dart';), then it will be accepted.

Upvotes: 1

Nadeem Siddique
Nadeem Siddique

Reputation: 2128

From Documentation:

Unlike Java, Dart does not have the keywords public, protected, and private. If an identifier starts with an underscore _, it’s private to its library.

What it means that privacy exist at library level rather than class level.

To use that in other files you will need to import the library in your file.

Upvotes: 0

Related Questions