Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Native implementation of an abstract method

Is it permitted in Java to have a an abstract method within a class and then have it's implementation in an other with a native language using JNI.

example:

abstract class Mommy {
abstract protected void call();
}
class Son extends Mommy {
 native protected void call() /*
'native code'
*/
}

What is the expected behaviour is it a runtime error that may occurs or everything is fine with "workaround" ?

like image 747
Hassam Abdelillah Avatar asked Jun 12 '17 12:06

Hassam Abdelillah


People also ask

How do you implement an abstract method?

An abstract method doesn't have any implementation (method body). A class containing abstract methods should also be abstract. We cannot create objects of an abstract class. To implement features of an abstract class, we inherit subclasses from it and create objects of the subclass.

What is native implementation?

Native methods are implemented mostly in C and compiled to native code which runs directly on the machine. This is in contrast to normal methods, which are implemented in Java and compiled to Java byte code, which is executed by the Java Virtual Machine (JVM).

How do you give default implementation in the abstract method?

If you want to have default implementation of a method in your abstract class, you have to use non-abstract methods. In abstract classes, you can declare fields with or without static and final modifiers. And concrete methods can be not just public, but also default, protected or private.

Can abstract method have default implementation?

Abstract class in Java is similar to interface except that it can contain default method implementation. An abstract class can have an abstract method without body and it can have methods with implementation also. abstract keyword is used to create a abstract class and method.


2 Answers

What is the expected behaviour is it a runtime error that may occurs or everything is fine with "workaround" ?

Provided that you implement the native method (correctly) and load the native library containing the implementation, then everything works.

I wonder if bug prone or against any good/best practices?

Nope, and nope.

Or at least, it is not more bug prone or more against "best practice" than any use of native code.

By the way, you really ought to read James Bach's "No Best Practices" article before you bandy around dodgy terms like "best practice".

like image 93
Stephen C Avatar answered Oct 21 '22 18:10

Stephen C


Seems to be working just fine. This is quite cool solution in case you want to easily switch between native implementations.

https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo030

and description inside JNI Cookbook can give you quick overview on the solution

http://jnicookbook.owsiak.org/recipe-no-030/

like image 35
Oo.oO Avatar answered Oct 21 '22 17:10

Oo.oO