Extending Classes And Interfaces
As part of the native Android development you often have to inherit from classes and/or implement interfaces. NativeScript supports these scenarios as well.
Classes
Here is how the above is done in NativeScript:
Note: In the above
setEnabled
function thethis
keyword points to the JavaScript object that proxies the extended native instance. Thethis.super
property provides access to the base class method implementation.
Creating an anonymous Java class which extends from the base
Java java.lang.Object
class:
Creating a named Java class which extends from the
java.lang.Object
class will allow referring to the
class by its full package name (in AndroidManifest.xml, for
example):
One important thing to note when dealing with extending classes and implementing interfaces in NativeScript is that, unlike in Java - where you can extend an Abstract class with a new java.arbitrary.abstract.Class() { }, in NativeScript the class needs to be extended as per the previous examples - using the
extend
function on thejava.arbitrary.abstract.Class
, or using theextends
class syntax in TypeScript.
Interfaces
The next example shows how to implement an interface in
Java/Kotlin and NativeScript. The main difference between
inheriting classes and implementing interfaces in NativeScript
is the use of the extend
keyword. Basically, you
implement an interface by passing the
implementation object to the interface constructor
function. The syntax is identical to the
Java Anonymous Classes.
Alternatively you can use the following pattern for a named interface implementation:
Implementing multiple interfaces in NativeScript
Suppose you have the following interfaces in Java/Kotlin:
Implementing the interfaces is as easy in Java as writing:
The same result can be achieved in NativeScript by extending any valid object that inherits Java Object.
- In JavaScript - Declare an interfaces array in the implementation
-
Using Typescript syntax - apply a
decorator to the extended class (note
@Interfaces([...]
))
Using Javascript syntax - attach interfaces
array
to implementation object of the extend call
Limitations
- Implementing two interfaces with the same method signature will generate just 1 method. It is the implementor's responsibility to define how the method will behave for both interfaces
-
Implementing two interfaces with the same
method name, parameter number, but
different return type (
void a()
vsboolean a()
) will result in a compilation error
Notes
Java/Kotlin method overloads are handled by the developer by explicitly checking the
arguments
count of the invoked function
In addition to implementing interface methods, you can override methods of the extended class, and also declare your own methods that the new class should have.