File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes How do you instantiate this class? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "How do you instantiate this class?" Watch "How do you instantiate this class?" New topic
Author

How do you instantiate this class?

Simon Forth
Greenhorn

Joined: Nov 15, 2011
Posts: 20
If you have

what syntax is required to instantiate a class Hose object?


Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18991
    
    8

That would depend on what constructors were available.
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

If there no constructor, then compiler insert default no-argument constructor for your class.
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4491
    
    8

I suspect the question is really about the generic types. E.g. you can't exactly go:
new Hose<Hose<Hose<Hose<Hose<.. infinite number of Hoses.....>>>>>();
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4491
    
    8

I haven't worked out a way of instantiating it directly (without cheating and omitting the generics). I'd be interested to see a solution to that. But I can create a non-generic subclass that can then be instantiated:
Karthikeyan Kandasamy
Greenhorn

Joined: Apr 17, 2011
Posts: 14
You can create a Hose object without type and with type. I think, if you create a Hose object without type, it will use Hose as E.

Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4491
    
    8

Karthikeyan Kandasamy wrote:You can create a Hose object without type and with type. I think, if you create a Hose object without type, it will use Hose as E.

No, if you omit the type it's the same as leaving out the type when creating collections. You lose the type-safety completely.

The other approach you've used - creating a non-generic subclass - is the same as mine.
Karthikeyan Kandasamy
Greenhorn

Joined: Apr 17, 2011
Posts: 14
I came to that conclusion because of this code snippet. I tried passing an object to the Hose constructor and it gave a compiler error.




Error:

GenericSamples7.java:11: cannot find symbol
symbol : constructor Hose(java.lang.Object)
location: class genericsamples.Hose
Hose h2 = new Hose(new Object());
^
1 error
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4491
    
    8

Apologies, you're right.

If you don't give the generic type, then anywhere the compiler needs to know the type (like in that constructor) it uses the "erasure" of that type. Which, if the type has an upper bound, is that upper bound. So in this case, because it's E extends Hose, will be Hose.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: How do you instantiate this class?