0

I want to convert:

typedef byte   U8;

to OO like this:

public final class U8 extends Byte    { 
      U8( byte x  ){
          super(x); 
      } 
}; 

This results in an error "The type U8 cannot subclass final class byte".

Is there a simple way to do this?

Kevin Workman
  • 41,537
  • 9
  • 68
  • 107
Davidfi1
  • 97
  • 5

1 Answers1

2

The simple way to do this would be to reuse someone else's library. There are some leads in this Q&A:

What you are actually trying to do (extend java.lang.Byte) is both impossible (because the Byte class is final) and conceptually wrong. The sets of numbers represented by an unsigned byte and a signed byte are different. Therefore neither is conceptually a subtype of the other. If you model one as a Java subclass of the other, you will end up with type anomalies and runtime value checking to avoid them.


Finally, while this kind of modeling gives you a nice OO program, the downside is that you will take a significant performance hit relative to using primitive types and "tweaking" to deal with signed versus non-signed. You might be interested to know that there is a new API in Java 8 for doing unsigned operations on signed primitive types.

The API consists of new static methods in the existing wrapper classes.

Community
  • 1
  • 1
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Thank you all for yore answers. I took from the package org.joou the Ubyte but I am working in processing.org. I get the error "No enclosing instance is available due to sume intermediate constructor invocation" on all constructors. Can you help? – Davidfi1 May 04 '16 at 04:18
  • Bot without seeing your code. Ask a new Question with an MCVE included. – Stephen C May 04 '16 at 07:47