Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

on Abstract classes

 
Lalit Sha
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Problem:Create a class as abstract without including any
abstract methods and verify that you cannot create any
instances of that class.
Here I want to know,' cannot create instances of that
class ' means you cannot create any objects for that
class.I tried the following way.When I try to create an
object of the Abstract class in the TestTestAbstract class,
like,Abstract ab = new Abstract(), I get a compile error.
But when I try to create an array object ab, like,
Abstract[] ab = new Abstract[1], it works. Can anybody
explain why is this happening. An array is also an object.
For an abstract class when you cannot create objects, how
an array is only possible.
abstract class Abstract {
void print() {
System.out.println("Abstract class");
}
void print2() {
System.out.println("Abstract class");
}
}

class TestAbstract extends Abstract{
void print2() {
System.out.println("TestAbstract class");
}
}

public class TestTestAbstract {
public static void main (String[] args) {
Abstract[] ab = new Abstract[1];
ab[0] = new TestAbstract();
ab[0].print();
ab[0].print2();
}
}
 
Frank Carver
Sheriff
Posts: 6920
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't create an object of an abstract class, but you can crreate objects of classes which extend an abstract class. So if you have
abstract class Abs {}
class Conc extends Abs {}
you can't say
Abs a = new Abs();
but you can say
Conc c = new Conc();
Also, because you can always treat a class as if it is an object of a class which it extends, you can also say:
Abs c = new Conc();
which is equivalent to
Abs c = (Abs) new Conc();
Because you may want to have an array of these classes pretending to be their parents, you can also create an array of abstract classes. Remember that in Java, declaring an array doesn't cause any of the array elements to be created, all the elements are set to null. So we can say
Abs[] aa = new Abs[5];
and put some Concs in to it, but pretend they are Abs objects:
aa[0] = new Conc();
aa[1] = new Conc()
and so on.
 
Lalit Sha
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Frank. I understood it well now.
Lalit.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic