• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

A simple basic question about instance and object

 
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What difference between creating an instance of a class and creating an object of the class?

if we have:

public abstract class MyAbstractClass()
{
// set of abstract and non-abstract method come here
}

can we write :

MyAbstractClass abclass = MyAbstractClass.newInstance();

newInstance() returns a newly allocated instance of the class represented by this object. But we know abstract classes and interfaces cannot be instantiated. So is the statement
MyAbstractClass abclass = MyAbstractClass.newInstance(); true?

Please explain. I think I am wrong somewhere.
 
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

Creating a new instance of a class is same as creating an object of the class.

As far as Abstract classes/interfaces are concerned they can never be instantiated
i.e. you cannot tell AbstractClass ob = new AbstractClass(); anywhere in the code

- Ramu
 
Ranch Hand
Posts: 226
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
you could create a static method in the abstract class called newInstance() with the return type of MyAbstractClass that doesn't make it a constructor.

The implementation of newInstance() would have to be a factory type method that would have to choose a concrete subclass to return.

It couldn't do something like this



it would have to be something like



If you are trying to use the method newInstance in the Class class your code would have to be more like


Which when ran would throw an exception (java.lang.InstantiationException).
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic