This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes  on Abstract classes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark " on Abstract classes" Watch " on Abstract classes" New topic
Author

on Abstract classes

Lalit Sha
Greenhorn

Joined: Jan 11, 2001
Posts: 28
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

Joined: Jan 07, 1999
Posts: 6920
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.


Read about me at frankcarver.me ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
Lalit Sha
Greenhorn

Joined: Jan 11, 2001
Posts: 28
Thanks Frank. I understood it well now.
Lalit.
 
GeeCON Prague 2014
 
subject: on Abstract classes