-1

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?

5
  • 2
    Is there an easy way to subclass a final class? No. Commented May 2, 2016 at 4:31
  • You can not extends final class. Commented May 2, 2016 at 4:31
  • 2
    It is unclear what you're asking. Is there a simple way to do this? - A simple way to do what exactly? Extend a final class (by definition this can't be done)? Create a class that wraps byte similar to the Byte class? Commented May 2, 2016 at 4:41
  • byte is final class therefore we cant extends final class Commented May 2, 2016 at 4:49
  • Ermm ... I think you mean Byte not byte. (You cannot have a >>class<< with the name byte ... because it is a Java reserved word.) Commented May 2, 2016 at 5:02

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
Bot without seeing your code. Ask a new Question with an MCVE included.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.