java array of objects and inheritance - java

I have 3 classes, MainClass with main method, one abstract class named AbstractClass and Subclass which is to be extended with AbstractClass.
The array of objects is created in main method from type AbstractClass containing 1 member.
Then I initialize that 1 element of array as type Subclass( is this ok?).
The problem is I can't get to the getDataToExport() method of created object ( array[0] ) .
I suspect the problem occurs because the array is the AbstractClass type...
And the question: is this even possible to accomplish?
What I'm trying to do is use an array of type AbstractClass and fill it with objects made from different subclasses( in this code is just one->Subclass ) extended with AbstractClass but i can't get to the methods of that subclasses.
main class with main method
public class MainClass {
public static void main() {
AbstractClass array[]=new AbstractClass[1];
array[0]= new Subclass(); // is this even allowed?
System.out.println(array[0].getDataToExport()); // Problem!
}
}
abstract class
public abstract class AbstractClass {
}
Subclass which extends AbstractClass
public class Subclass extends AbstractClass {
private int dataToExport;
public Subclass(){
this.dataToExport=2;
}
public int getDataToExport() {
return dataToExport;
}
}

AbstractClass array[]=new AbstractClass[1];
array[0]= new Subclass(); // is this even allowed?
Yes, that's fine, but it means that when you later go to use it, you only have access to what's defined in AbstractClass (barring using a cast, but you want to avoid using casts wherever you can, and there's no need for one here).
The only real reason for making the array entries of type AbstractClass would be if you only want to interact with the members defined in that class. So for instance, in this case, you'd probably want to have the getDataToExport defined as an abstract method in the abstract class:
public abstract class AbstractClass {
public abstract int getDataToExport();
}
You might also consider looking at having an interface rather than an abstract class. Since a class can only derive from one base class, but can implement as many interfaces as it likes, unless there's a large body of common implementation that you'd be putting in the abstract base class, you're better off with an interface — because it doesn't put unnecessary constraints on the implementations of that interface. In fact, you're almost always better off with an interface; you can always also have an abstract base if you want.
So for instance:
public class MainClass {
public static void main() {
NiftyThingy array[]=new NiftyThingy[1];
array[0]= new NiftyThingyImplementation();
System.out.println(array[0].getDataToExport());
}
}
where
public interface NiftyThingy {
public int getDataToExport();
}
and
public class NiftyThingyImplementation implements NiftyThingy {
public int getDataToExport() {
return /* ... the data ... */;
}
}

You must declare getDataToExport() as an abstract method in AbstractClass.

You won't be able to get it because you are declaring an array of AbstractClass in order to see them you have two choices
Declare the common methods that you will use on the abstract class and declare them abstract. Override those methods in the subclasses. For example:
public abstract class AbstractClass {
public abstract int getDataToExport();
}
And every subclass will have to override that method or should be declared abstract too.
Create an array of Sublclass:
Subclass array[] = new Sublcass[1];
array[0] = new Subclass();
System.out.println(array[0].getDataToExport());

Yes, all this is perfectly fine. The only step you have missed is that you need to cast the instance of the object to the type that has the method you want. The usual way to do this is:
AbstractClass ac = array[0];
if (ac instanceof Subclass) {
System.out.println(((Subclass)ac).getDataToExport()); // No problem!
}
However you might want to think about doing this another way. For example, implement a default version of getDataToExport in the abstract class that returns null. That way you don't have to do the cast or the instanceof test.

AbstractClass array[]=new AbstractClass[1];
array[0]= new Subclass(); // is this even allowed?
Indeed is valid as SubClass is a derived class of AbstractClass. The reason why
System.out.println(array[0].getDataToExport());
fails is because the compiler cannot find AbstractClass.getDataToExport() method. It's only SubClass that has the method and not its parent.
There are couple of ways to solve this:
Add an abstract method getDataToExport to the AbstractClass like so:
public abstract class AbstractClass {
public abstract int getDataToExport();
}
OR, Typecast your variable to its derived (concrete) class that has the getDataToExport() method, like so:
if (array[0] instanceof SubClass) {
System.out.println(((SubClass)array[0]).getDataToExport());
}
the instanceof operator simply states that the attribute is of a class X (where X is SubClass).

Related

Could not instantiate the type (Class)? [duplicate]

What is an "abstract class" in Java?
An abstract class is a class which cannot be instantiated. An abstract class is used by creating an inheriting subclass that can be instantiated. An abstract class does a few things for the inheriting subclass:
Define methods which can be used by the inheriting subclass.
Define abstract methods which the inheriting subclass must implement.
Provide a common interface which allows the subclass to be interchanged with all other subclasses.
Here's an example:
abstract public class AbstractClass
{
abstract public void abstractMethod();
public void implementedMethod() { System.out.print("implementedMethod()"); }
final public void finalMethod() { System.out.print("finalMethod()"); }
}
Notice that "abstractMethod()" doesn't have any method body. Because of this, you can't do the following:
public class ImplementingClass extends AbstractClass
{
// ERROR!
}
There's no method that implements abstractMethod()! So there's no way for the JVM to know what it's supposed to do when it gets something like new ImplementingClass().abstractMethod().
Here's a correct ImplementingClass.
public class ImplementingClass extends AbstractClass
{
public void abstractMethod() { System.out.print("abstractMethod()"); }
}
Notice that you don't have to define implementedMethod() or finalMethod(). They were already defined by AbstractClass.
Here's another correct ImplementingClass.
public class ImplementingClass extends AbstractClass
{
public void abstractMethod() { System.out.print("abstractMethod()"); }
public void implementedMethod() { System.out.print("Overridden!"); }
}
In this case, you have overridden implementedMethod().
However, because of the final keyword, the following is not possible.
public class ImplementingClass extends AbstractClass
{
public void abstractMethod() { System.out.print("abstractMethod()"); }
public void implementedMethod() { System.out.print("Overridden!"); }
public void finalMethod() { System.out.print("ERROR!"); }
}
You can't do this because the implementation of finalMethod() in AbstractClass is marked as the final implementation of finalMethod(): no other implementations will be allowed, ever.
Now you can also implement an abstract class twice:
public class ImplementingClass extends AbstractClass
{
public void abstractMethod() { System.out.print("abstractMethod()"); }
public void implementedMethod() { System.out.print("Overridden!"); }
}
// In a separate file.
public class SecondImplementingClass extends AbstractClass
{
public void abstractMethod() { System.out.print("second abstractMethod()"); }
}
Now somewhere you could write another method.
public tryItOut()
{
ImplementingClass a = new ImplementingClass();
AbstractClass b = new ImplementingClass();
a.abstractMethod(); // prints "abstractMethod()"
a.implementedMethod(); // prints "Overridden!" <-- same
a.finalMethod(); // prints "finalMethod()"
b.abstractMethod(); // prints "abstractMethod()"
b.implementedMethod(); // prints "Overridden!" <-- same
b.finalMethod(); // prints "finalMethod()"
SecondImplementingClass c = new SecondImplementingClass();
AbstractClass d = new SecondImplementingClass();
c.abstractMethod(); // prints "second abstractMethod()"
c.implementedMethod(); // prints "implementedMethod()"
c.finalMethod(); // prints "finalMethod()"
d.abstractMethod(); // prints "second abstractMethod()"
d.implementedMethod(); // prints "implementedMethod()"
d.finalMethod(); // prints "finalMethod()"
}
Notice that even though we declared b an AbstractClass type, it displays "Overriden!". This is because the object we instantiated was actually an ImplementingClass, whose implementedMethod() is of course overridden. (You may have seen this referred to as polymorphism.)
If we wish to access a member specific to a particular subclass, we must cast down to that subclass first:
// Say ImplementingClass also contains uniqueMethod()
// To access it, we use a cast to tell the runtime which type the object is
AbstractClass b = new ImplementingClass();
((ImplementingClass)b).uniqueMethod();
Lastly, you cannot do the following:
public class ImplementingClass extends AbstractClass, SomeOtherAbstractClass
{
... // implementation
}
Only one class can be extended at a time. If you need to extend multiple classes, they have to be interfaces. You can do this:
public class ImplementingClass extends AbstractClass implements InterfaceA, InterfaceB
{
... // implementation
}
Here's an example interface:
interface InterfaceA
{
void interfaceMethod();
}
This is basically the same as:
abstract public class InterfaceA
{
abstract public void interfaceMethod();
}
The only difference is that the second way doesn't let the compiler know that it's actually an interface. This can be useful if you want people to only implement your interface and no others. However, as a general beginner rule of thumb, if your abstract class only has abstract methods, you should probably make it an interface.
The following is illegal:
interface InterfaceB
{
void interfaceMethod() { System.out.print("ERROR!"); }
}
You cannot implement methods in an interface. This means that if you implement two different interfaces, the different methods in those interfaces can't collide. Since all the methods in an interface are abstract, you have to implement the method, and since your method is the only implementation in the inheritance tree, the compiler knows that it has to use your method.
A Java class becomes abstract under the following conditions:
1. At least one of the methods is marked as abstract:
public abstract void myMethod()
In that case the compiler forces you to mark the whole class as abstract.
2. The class is marked as abstract:
abstract class MyClass
As already said: If you have an abstract method the compiler forces you to mark the whole class as abstract. But even if you don't have any abstract method you can still mark the class as abstract.
Common use:
A common use of abstract classes is to provide an outline of a class similar like an interface does. But unlike an interface it can already provide functionality, i.e. some parts of the class are implemented and some parts are just outlined with a method declaration. ("abstract")
An abstract class cannot be instantiated, but you can create a concrete class based on an abstract class, which then can be instantiated. To do so you have to inherit from the abstract class and override the abstract methods, i.e. implement them.
A class that is declared using the abstract keyword is known as abstract class.
Abstraction is a process of hiding the data implementation details, and showing only functionality to the user. Abstraction lets you focus on what the object does instead of how it does it.
Main things of abstract class
An abstract class may or may not contain abstract methods.There can be non abstract methods.
An abstract method is a method that is declared without an
implementation (without braces, and followed by a semicolon), like this:
ex : abstract void moveTo(double deltaX, double deltaY);
If a class has at least one abstract method then that class must be abstract
Abstract classes may not be instantiated (You are not allowed to create object of Abstract class)
To use an abstract class, you have to inherit it from another class. Provide implementations to all the abstract methods in it.
If you inherit an abstract class, you have to provide implementations to all the abstract methods in it.
Declare abstract class
Specifying abstract keyword before the class during declaration makes it abstract. Have a look at the code below:
abstract class AbstractDemo{ }
Declare abstract method
Specifying abstract keyword before the method during declaration makes it abstract. Have a look at the code below,
abstract void moveTo();//no body
Why we need to abstract classes
In an object-oriented drawing application, you can draw circles, rectangles, lines, Bezier curves, and many other graphic objects. These objects all have certain states (for ex -: position, orientation, line color, fill color) and behaviors (for ex -: moveTo, rotate, resize, draw) in common. Some of these states and behaviors are the same for all graphic objects (for ex : fill color, position, and moveTo). Others require different implementation(for ex: resize or draw). All graphic objects must be able to draw or resize themselves, they just differ in how they do it.
This is a perfect situation for an abstract superclass. You can take advantage of the similarities, and declare all the graphic objects to inherit from the same abstract parent object (for ex : GraphicObject) as shown in the following figure.
First, you declare an abstract class, GraphicObject, to provide member variables and methods that are wholly shared by all subclasses, such as the current position and the moveTo method. GraphicObject also declared abstract methods, such as draw or resize, that need to be a implemented by all subclasses but must be implemented in different ways. The GraphicObject class can look something like this:
abstract class GraphicObject {
void moveTo(int x, int y) {
// Inside this method we have to change the position of the graphic
// object according to x,y
// This is the same in every GraphicObject. Then we can implement here.
}
abstract void draw(); // But every GraphicObject drawing case is
// unique, not common. Then we have to create that
// case inside each class. Then create these
// methods as abstract
abstract void resize();
}
Usage of abstract method in sub classes
Each non abstract subclasses of GraphicObject, such as Circle and Rectangle, must provide implementations for the draw and resize methods.
class Circle extends GraphicObject {
void draw() {
//Add to some implementation here
}
void resize() {
//Add to some implementation here
}
}
class Rectangle extends GraphicObject {
void draw() {
//Add to some implementation here
}
void resize() {
//Add to some implementation here
}
}
Inside the main method you can call all methods like this:
public static void main(String args[]){
GraphicObject c = new Circle();
c.draw();
c.resize();
c.moveTo(4,5);
}
Ways to achieve abstraction in Java
There are two ways to achieve abstraction in java
Abstract class (0 to 100%)
Interface (100%)
Abstract class with constructors, data members, methods, etc
abstract class GraphicObject {
GraphicObject (){
System.out.println("GraphicObject is created");
}
void moveTo(int y, int x) {
System.out.println("Change position according to "+ x+ " and " + y);
}
abstract void draw();
}
class Circle extends GraphicObject {
void draw() {
System.out.println("Draw the Circle");
}
}
class TestAbstract {
public static void main(String args[]){
GraphicObject grObj = new Circle ();
grObj.draw();
grObj.moveTo(4,6);
}
}
Output:
GraphicObject is created
Draw the Circle
Change position according to 6 and 4
Remember two rules:
If the class has few abstract methods and few concrete methods,
declare it as an abstract class.
If the class has only abstract methods, declare it as an interface.
References:
TutorialsPoint - Java Abstraction
BeginnersBook - Java Abstract Class Method
Java Docs - Abstract Methods and Classes
JavaPoint - Abstract Class in Java
It's a class that cannot be instantiated, and forces implementing classes to, possibly, implement abstract methods that it outlines.
Simply speaking, you can think of an abstract class as like an Interface with a bit more capabilities.
You cannot instantiate an Interface, which also holds for an abstract class.
On your interface you can just define the method headers and ALL of the implementers are forced to implement all of them. On an abstract class you can also define your method headers but here - to the difference of the interface - you can also define the body (usually a default implementation) of the method. Moreover when other classes extend (note, not implement and therefore you can also have just one abstract class per child class) your abstract class, they are not forced to implement all of your methods of your abstract class, unless you specified an abstract method (in such case it works like for interfaces, you cannot define the method body).
public abstract class MyAbstractClass{
public abstract void DoSomething();
}
Otherwise for normal methods of an abstract class, the "inheriters" can either just use the default behavior or override it, as usual.
Example:
public abstract class MyAbstractClass{
public int CalculateCost(int amount){
//do some default calculations
//this can be overriden by subclasses if needed
}
//this MUST be implemented by subclasses
public abstract void DoSomething();
}
From oracle documentation
Abstract Methods and Classes:
An abstract class is a class that is declared abstract—it may or may not include abstract methods
Abstract classes cannot be instantiated, but they can be subclassed
An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:
abstract void moveTo(double deltaX, double deltaY);
If a class includes abstract methods, then the class itself must be declared abstract, as in:
public abstract class GraphicObject {
// declare fields
// declare nonabstract methods
abstract void draw();
}
When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract.
Since abstract classes and interfaces are related, have a look at below SE questions:
What is the difference between an interface and abstract class?
How should I have explained the difference between an Interface and an Abstract class?
Get your answers here:
Abstract class vs Interface in Java
Can an abstract class have a final method?
BTW - those are question you asked recently. Think about a new question to build up reputation...
Edit:
Just realized, that the posters of this and the referenced questions have the same or at least similiar name but the user-id is always different. So either, there's a technical problem, that keyur has problems logging in again and finding the answers to his questions or this is a sort of game to entertain the SO community ;)
Little addition to all these posts.
Sometimes you may want to declare a
class and yet not know how to define
all of the methods that belong to that
class. For example, you may want to
declare a class called Writer and
include in it a member method called
write(). However, you don't know how to code write() because it is
different for each type of Writer
devices. Of course, you plan to handle
this by deriving subclass of Writer,
such as Printer, Disk, Network and
Console.
An abstract class can not be directly instantiated, but must be derived from to be usable. A class MUST be abstract if it contains abstract methods: either directly
abstract class Foo {
abstract void someMethod();
}
or indirectly
interface IFoo {
void someMethod();
}
abstract class Foo2 implements IFoo {
}
However, a class can be abstract without containing abstract methods. Its a way to prevent direct instantation, e.g.
abstract class Foo3 {
}
class Bar extends Foo3 {
}
Foo3 myVar = new Foo3(); // illegal! class is abstract
Foo3 myVar = new Bar(); // allowed!
The latter style of abstract classes may be used to create "interface-like" classes. Unlike interfaces an abstract class is allowed to contain non-abstract methods and instance variables. You can use this to provide some base functionality to extending classes.
Another frequent pattern is to implement the main functionality in the abstract class and define part of the algorithm in an abstract method to be implemented by an extending class. Stupid example:
abstract class Processor {
protected abstract int[] filterInput(int[] unfiltered);
public int process(int[] values) {
int[] filtered = filterInput(values);
// do something with filtered input
}
}
class EvenValues extends Processor {
protected int[] filterInput(int[] unfiltered) {
// remove odd numbers
}
}
class OddValues extends Processor {
protected int[] filterInput(int[] unfiltered) {
// remove even numbers
}
}
Solution - base class (abstract)
public abstract class Place {
String Name;
String Postcode;
String County;
String Area;
Place () {
}
public static Place make(String Incoming) {
if (Incoming.length() < 61) return (null);
String Name = (Incoming.substring(4,26)).trim();
String County = (Incoming.substring(27,48)).trim();
String Postcode = (Incoming.substring(48,61)).trim();
String Area = (Incoming.substring(61)).trim();
Place created;
if (Name.equalsIgnoreCase(Area)) {
created = new Area(Area,County,Postcode);
} else {
created = new District(Name,County,Postcode,Area);
}
return (created);
}
public String getName() {
return (Name);
}
public String getPostcode() {
return (Postcode);
}
public String getCounty() {
return (County);
}
public abstract String getArea();
}
What is Abstract class?
Ok! lets take an example you known little bit about chemistry we have an element carbon(symbol C).Carbon has some basic atomic structure which you can't change but using carbon you can make so many compounds like (CO2),Methane(CH4),Butane(C4H10).
So Here carbon is abstract class and you do not want to change its basic structure however you want their childrens(CO2,CH4 etc) to use it.But in their own way
An abstract class is a class that is declared abstract — it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.
In other words, a class that is declared with abstract keyword, is known as abstract class in java. It can have abstract(method without body) and non-abstract methods (method with body).
Important Note:-
Abstract classes cannot be used to instantiate objects, they can be used to create object references, because Java's approach to run-time Polymorphism is implemented through the use of superclass references. Thus, it must be possible to create a reference to an abstract class so that it can be used to point to a subclass object. You will see this feature in the below example
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){
System.out.println("running safely..");
}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
An abstract class is one that isn't fully implemented but provides something of a blueprint for subclasses. It may be partially implemented in that it contains fully-defined concrete methods, but it can also hold abstract methods. These are methods with a signature but no method body. Any subclass must define a body for each abstract method, otherwise it too must be declared abstract.
Because abstract classes cannot be instantiated, they must be extended by at least one subclass in order to be utilized. Think of the abstract class as the generic class, and the subclasses are there to fill in the missing information.
Class which can have both concrete and non-concrete methods i.e. with and without body.
Methods without implementation must contain 'abstract' keyword.
Abstract class can't be instantiated.
It do nothing, just provide a common template that will be shared for it's subclass

Why is it ok to do "new" to an abstract class? [duplicate]

During one of my interview, I was asked "If we can instantiate an abstract class?"
My reply was "No. we can't". But, interviewer told me "Wrong, we can."
I argued a bit on this. Then he told me to try this myself at home.
abstract class my {
public void mymethod() {
System.out.print("Abstract");
}
}
class poly {
public static void main(String a[]) {
my m = new my() {};
m.mymethod();
}
}
Here, I'm creating instance of my class and calling method of abstract class. Can anyone please explain this to me? Was I really wrong during my interview?
Here, i'm creating instance of my class
No, you are not creating the instance of your abstract class here. Rather you are creating an instance of an anonymous subclass of your abstract class. And then you are invoking the method on your abstract class reference pointing to subclass object.
This behaviour is clearly listed in JLS - Section # 15.9.1: -
If the class instance creation expression ends in a class body, then
the class being instantiated is an anonymous class. Then:
If T denotes a class, then an anonymous direct subclass of the class named by T is declared. It is a compile-time error if the
class denoted by T is a final class.
If T denotes an interface, then an anonymous direct subclass of Object that implements the interface named by T is declared.
In either case, the body of the subclass is the ClassBody given in the class instance creation expression.
The class being instantiated is the anonymous subclass.
Emphasis mine.
Also, in JLS - Section # 12.5, you can read about the Object Creation Process. I'll quote one statement from that here: -
Whenever a new class instance is created, memory space is allocated
for it with room for all the instance variables declared in the class
type and all the instance variables declared in each superclass of the
class type, including all the instance variables that may be hidden.
Just before a reference to the newly created object is returned as the
result, the indicated constructor is processed to initialize the new
object using the following procedure:
You can read about the complete procedure on the link I provided.
To practically see that the class being instantiated is an Anonymous SubClass, you just need to compile both your classes. Suppose you put those classes in two different files:
My.java:
abstract class My {
public void myMethod() {
System.out.print("Abstract");
}
}
Poly.java:
class Poly extends My {
public static void main(String a[]) {
My m = new My() {};
m.myMethod();
}
}
Now, compile both your source files:
javac My.java Poly.java
Now in the directory where you compiled the source code, you will see the following class files:
My.class
Poly$1.class // Class file corresponding to anonymous subclass
Poly.class
See that class - Poly$1.class. It's the class file created by the compiler corresponding to the anonymous subclass you instantiated using the below code:
new My() {};
So, it's clear that there is a different class being instantiated. It's just that, that class is given a name only after compilation by the compiler.
In general, all the anonymous subclasses in your class will be named in this fashion:
Poly$1.class, Poly$2.class, Poly$3.class, ... so on
Those numbers denote the order in which those anonymous classes appear in the enclosing class.
The above instantiates an anonymous inner class which is a subclass of the my abstract class. It's not strictly equivalent to instantiating the abstract class itself. OTOH, every subclass instance is an instance of all its super classes and interfaces, so most abstract classes are indeed instantiated by instantiating one of their concrete subclasses.
If the interviewer just said "wrong!" without explaining, and gave this example, as a unique counterexample, I think he doesn't know what he's talking about, though.
= my() {}; means that there's an anonymous implementation, not simple instantiation of an object, which should have been : = my(). You can never instantiate an abstract class.
Just observations you could make:
Why poly extends my? This is useless...
What is the result of the compilation? Three files: my.class, poly.class and poly$1.class
If we can instantiate an abstract class like that, we can instantiate an interface too... weird...
Can we instantiate an abstract class?
No, we can't. What we can do is, create an anonymous class (that's the third file) and instantiate it.
What about a super class instantiation?
The abstract super class is not instantiated by us but by java.
EDIT: Ask him to test this
public static final void main(final String[] args) {
final my m1 = new my() {
};
final my m2 = new my() {
};
System.out.println(m1 == m2);
System.out.println(m1.getClass().toString());
System.out.println(m2.getClass().toString());
}
output is:
false
class my$1
class my$2
You can simply answers, in just one line
No, you can never instance Abstract Class
But, interviewer still not agree, then you can tell him/her
all you can do is, you can create an Anonymous Class.
And, according to Anonymous class, class declared and instantiate at the same place/line
So, it might be possible that, interviewer would be interested to check your confidence level and how much you know about the OOPs .
The technical part has been well-covered in the other answers, and it mainly ends in:
"He is wrong, he doesn't know stuff, ask him to join SO and get it all cleared :)"
I would like to address the fact(which has been mentioned in other answers) that this might be a stress-question and is an important tool for many interviewers to know more about you and how do you react to difficult and unusual situations. By giving you incorrect codes, he probably wanted to see if you argued back. To know whether you have the confidence to stand up against your seniors in situations similar to this.
P.S: I don't know why but I have a feeling that the interviewer has read this post.
Abstract classes cannot be instantiated, but they can be subclassed. See This Link
The best example is
Although Calender class has a abstract method getInstance(), but when you say Calendar calc=Calendar.getInstance();
calc is referring to the class instance of class GregorianCalendar as "GregorianCalendar extends Calendar "
Infact annonymous inner type allows you to create a no-name subclass of the abstract class and an instance of this.
Technical Answer
Abstract classes cannot be instantiated - this is by definition and design.
From the JLS, Chapter 8. Classes:
A named class may be declared abstract (§8.1.1.1) and must be declared
abstract if it is incompletely implemented; such a class cannot be
instantiated, but can be extended by subclasses.
From JSE 6 java doc for Classes.newInstance():
InstantiationException - if this Class represents an abstract class, an interface, an array
class, a primitive type, or void; or if the class has no nullary constructor; or if the
instantiation fails for some other reason.
You can, of course, instantiate a concrete subclass of an abstract class (including an anonymous subclass) and also carry out a typecast of an object reference to an abstract type.
A Different Angle On This - Teamplay & Social Intelligence:
This sort of technical misunderstanding happens frequently in the real world when we deal with complex technologies and legalistic specifications.
"People Skills" can be more important here than "Technical Skills". If competitively and aggressively trying to prove your side of the argument, then you could be theoretically right, but you could also do more damage in having a fight / damaging "face" / creating an enemy than it is worth. Be reconciliatory and understanding in resolving your differences. Who knows - maybe you're "both right" but working off slightly different meanings for terms??
Who knows - though not likely, it is possible the interviewer deliberately introduced a small conflict/misunderstanding to put you into a challenging situation and see how you behave emotionally and socially. Be gracious and constructive with colleagues, follow advice from seniors, and follow through after the interview to resolve any challenge/misunderstanding - via email or phone call. Shows you're motivated and detail-oriented.
It is a well-established fact that abstract class can not be instantiated as everyone answered.
When the program defines anonymous class, the compiler actually creates a new class with different name (has the pattern EnclosedClassName$n where n is the anonymous class number)
So if you decompile this Java class you will find the code as below:
my.class
abstract class my {
public void mymethod()
{
System.out.print("Abstract");
}
}
poly$1.class (the generated class of the "anonymous class")
class poly$1 extends my
{
}
ploly.cass
public class poly extends my
{
public static void main(String[] a)
{
my m = new poly.1(); // instance of poly.1 class NOT the abstract my class
m.mymethod();
}
}
About Abstract Classes
Cannot create object of an abstract class
Can create variables (can behave like datatypes)
If a child can not override at least of one abstract method of the parent, then child also becomes abstract
Abstract classes are useless without child classes
The purpose of an abstract class is to behave like a base. In inheritance hierarchy you will see abstract classes towards the top.
No, you can't instantite an abstract class.We instantiate only anonymous class.In abstract class we declare abstract methods and define concrete methods only.
Extending a class doesn't mean that you are instantiating the class. Actually, in your case you are creating an instance of the subclass.
I am pretty sure that abstract classes do not allow initiating. So, I'd say no: you can't instantiate an abstract class. But, you can extend it / inherit it.
You can't directly instantiate an abstract class. But it doesn't mean that you can't get an instance of class (not actully an instance of original abstract class) indirectly. I mean you can not instantiate the orginial abstract class, but you can:
Create an empty class
Inherit it from abstract class
Instantiate the dervied class
So you get access to all the methods and properties in an abstract class via the derived class instance.
It's impossible to instantiate an abstract class.
What you really can do, has implement some common methods in an abstract class and let others unimplemented (declaring them abstract) and let the concrete descender implement them depending on their needs.
Then you can make a factory, which returns an instance of this abstract class (actually his implementer). In the factory you then decide, which implementer to choose. This is known as a factory design pattern:
public abstract class AbstractGridManager {
private LifecicleAlgorithmIntrface lifecicleAlgorithm;
// ... more private fields
//Method implemented in concrete Manager implementors
abstract public Grid initGrid();
//Methods common to all implementors
public Grid calculateNextLifecicle(Grid grid){
return this.getLifecicleAlgorithm().calculateNextLifecicle(grid);
}
public LifecicleAlgorithmIntrface getLifecicleAlgorithm() {
return lifecicleAlgorithm;
}
public void setLifecicleAlgorithm(LifecicleAlgorithmIntrface lifecicleAlgorithm) {
this.lifecicleAlgorithm = lifecicleAlgorithm;
}
// ... more common logic and getters-setters pairs
}
The concrete implementer only needs to implement the methods declared as abstract, but will have access to the logic implemented in those classes in an abstract class, which are not declared abstract:
public class FileInputGridManager extends AbstractGridManager {
private String filePath;
//Method implemented in concrete Manager implementors
abstract public Grid initGrid();
public class FileInputGridManager extends AbstractGridManager {
private String filePath;
//Method implemented in concrete Manager implementors
abstract public Grid initGrid();
public Grid initGrid(String filePath) {
List<Cell> cells = new ArrayList<>();
char[] chars;
File file = new File(filePath); // for example foo.txt
// ... more logic
return grid;
}
}
Then finally the factory looks something like this:
public class GridManagerFactory {
public static AbstractGridManager getGridManager(LifecicleAlgorithmIntrface lifecicleAlgorithm, String... args){
AbstractGridManager manager = null;
// input from the command line
if(args.length == 2){
CommandLineGridManager clManager = new CommandLineGridManager();
clManager.setWidth(Integer.parseInt(args[0]));
clManager.setHeight(Integer.parseInt(args[1]));
// possibly more configuration logic
...
manager = clManager;
}
// input from the file
else if(args.length == 1){
FileInputGridManager fiManager = new FileInputGridManager();
fiManager.setFilePath(args[0]);
// possibly more method calls from abstract class
...
manager = fiManager ;
}
//... more possible concrete implementors
else{
manager = new CommandLineGridManager();
}
manager.setLifecicleAlgorithm(lifecicleAlgorithm);
return manager;
}
}
The receiver of AbstractGridManager would call the methods on him and get the logic, implemented in the concrete descender (and partially in the abstract class methods) without knowing what is the concrete implementation he got. This is also known as inversion of control or dependency injection.
You can say: we can't instantiate an abstract class, but we can use new keyword to create an anonymous class instance by just adding {} as implement body at the the end of the abstract class.
No, we can't create the object of abstract class, but create the reference variable of the abstract class. The reference variable is used to refer to the objects of derived classes (Sub classes of Abstract class)
Here is the example that illustrates this concept
abstract class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
// area is now an abstract method
abstract double area();
}
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
}
// override area for rectangle
double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Figure {
Triangle(double a, double b) {
super(a, b);
}
// override area for right triangle
double area() {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
class AbstractAreas {
public static void main(String args[]) {
// Figure f = new Figure(10, 10); // illegal now
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref; // this is OK, no object is created
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
}
}
Here we see that we cannot create the object of type Figure but we can create a reference variable of type Figure. Here we created a reference variable of type Figure and Figure Class reference variable is used to refer to the objects of Class Rectangle and Triangle.
Actually we can not create an object of an abstract class directly. What we create is a reference variable of an abstract call. The reference variable is used to Refer to the object of the class which inherits the Abstract class i.e. the subclass of the abstract class.

How to access the members of the concrete class using the reference variable of the abstract class

My abstract class has only three methods. My concrete class which extends the abstract class has price,name,packing. how can i access those properties using the reference variable of abstract class having instance of the concrete class. Directly i can't access any of the get set methods of the concrete class using this reference variable. Is there any special pattern for this problem????
According to my design, i have to assign the instance of the concrete class to the reference variable of the abstract class. I can't create the direct object of the concrete class.
With a reference to the abstract class alone, you can't do much.
However, you can type cast it to the corresponding concrete class.
eg: if you have class A and class B extends class A, you can do something like
if(obj instanceof B){
//type cast obj to class B here and call the respective method of B
((B)obj).concreteClassMethod();
}
Here obj is the reference variable of the abstract class A. This way, you can access any method (or public property) of class B, keeping the reference, however as class A.
Example:
First, you declare an abstract class, GraphicObject, to provide member variables and methods that are wholly shared by all subclasses, such as the current position and the moveTo method. GraphicObject also declares abstract methods for methods, such as draw or resize, that need to be implemented by all subclasses but must be implemented in different ways. The GraphicObject class can look something like this:
abstract class GraphicObject {
int x, y;
...
void moveTo(int newX, int newY) {
...
}
abstract void draw();
abstract void resize();
}
Each nonabstract subclass of GraphicObject, such as Circle and Rectangle, must provide implementations for the draw and resize methods:
class Circle extends GraphicObject {
void draw() {
...
}
void resize() {
...
}
}
class Rectangle extends GraphicObject {
void draw() {
...
}
void resize() {
...
}
}
than to acces to the father variable classes you can use: super.(variable)
only if the variable is public or protected.
If the variable is private, you will use get and set methods.
My abstract class has only three methods. My concrete class which extends the abstract class has price,name,packing.
I take it these abstract class methods are not the same as the three concrete class methods. Fine, I'll call these unnamed methods the mystery methods. If it turns out they are the same then just delete the mystery methods you'll see below.
how can i access those properties using the reference variable of abstract class having instance of the concrete class.
By injecting the dependency.
Directly i can't access any of the get set methods of the concrete class using this reference variable.
If they only exist on the concrete class this is no surprise. The only reason not to add them to the abstract class as #JBNizet suggests is if you don't want them exposed to client code. This is a reasonable concern but there is a better way to handle it.
Is there any special pattern for this problem????
Patterns are solutions not problems. What you say you're doing is structurally close to the http://en.wikipedia.org/wiki/Composite_pattern but you have the composition going in the wrong direction. I don't think the composite pattern is going to be what you want here.
According to my design, i have to assign the instance of the concrete class to the reference variable of the abstract class. I can't create the direct object of the concrete class.
There is a way to achieve this without using instanceof and more importantly without the Abstract class even knowing that the Concrete class exists.
public class Driver {
public static void main(String[] args) {
Composition compositionInstance = new Composition( new Concrete() );
System.out.println(compositionInstance);
}
}
public class Composition {
Abstract abstractInstance;
Composition(Abstract abstractInstance) {
if (abstractInstance == null) { throw new IllegalArgumentException("may not be null"); }
this.abstractInstance = abstractInstance;//concrete assigned to abstract ref var
}
public String toString() {
return String.format( "Price: %s, Name: %s, Packaging: %s",
abstractInstance.getPrice(),
abstractInstance.getName(),
abstractInstance.getPackaging() );
}
}
public abstract class Abstract {
void mysteryMethod1() {}
void mysteryMethod2() {}
void mysteryMethod3() {}
abstract String getPrice();
abstract String getName();
abstract String getPackaging();
}
public class Concrete extends Abstract {
String getPrice() {return "42";}
String getName() {return "My Concret Product";}
String getPackaging() {return "cardboard box";}
}
A lot of classes but they are very simple. These class names are terrible so don't imitate them.
Driver doesn't have to touch the getters since it can let Composition do that for it. It only knows how to build Composition and Concrete. It doesn't get chatty with them.
Composition only has to know how to talk to Abstract. It has no idea how to build one or exactly what concrete instance it might get.
Abstract only knows about it self. Doesn't know anyone else. It doesn't want to know.
Concrete only knows about abstract.
By writing the code this way it is kept flexible. It should be easy to make changes as requirements change.
This wasn't written following any set pattern. What it follows are the S.O.L.I.D. principles.

how to copy SubClass object in BaseClass copy constructor

I would like to make copy of SubClass object in BaseClass constructor. I need that the following code execute correctly.
class BaseClass{
BaseClass() {}
BaseClass(BaseClass base) {
//TODO: how to implement?
}
}
class SubClass extends BaseClass {
SubClass() {}
}
public class Test {
public static void main(String[] args) {
BaseClass sub = new SubClass();
BaseClass subCopy = new BaseClass(sub);
if (subCopy instanceof SubClass) {
// need to be true
}
}
}
Is it even possible? If yes how can I do it? Else how can I get similar effect?
It's not possible. A constructor of class A gives you an instance of A, no way to circumvent this. Why not instantiate the subclass explicitly?
Another possibility might involve a static factory method like:
public static BaseClass create(BaseClass input) {
// return BaseClass or subclass
}
It seems like you want the object of BaseClass to be an instance of SubClass which extends BaseClass.
Is it even possible?
-No. It is not possible.
The instanceof operator returns true if the variable on left side satisfies IS-A condition of the variable or class on the left side.
The SubClass IS-A BaseClass since it extends BaseClass. But the BaseClass can never be a SubClass, since it can't extend SubClass.
You seems to be having a design upside-down. If you need to do what you are asking then you need to re-think over your design. Ideally in your subclass constructor, you should be copying or initializing the base class properties by calling super().

Can we instantiate an abstract class?

During one of my interview, I was asked "If we can instantiate an abstract class?"
My reply was "No. we can't". But, interviewer told me "Wrong, we can."
I argued a bit on this. Then he told me to try this myself at home.
abstract class my {
public void mymethod() {
System.out.print("Abstract");
}
}
class poly {
public static void main(String a[]) {
my m = new my() {};
m.mymethod();
}
}
Here, I'm creating instance of my class and calling method of abstract class. Can anyone please explain this to me? Was I really wrong during my interview?
Here, i'm creating instance of my class
No, you are not creating the instance of your abstract class here. Rather you are creating an instance of an anonymous subclass of your abstract class. And then you are invoking the method on your abstract class reference pointing to subclass object.
This behaviour is clearly listed in JLS - Section # 15.9.1: -
If the class instance creation expression ends in a class body, then
the class being instantiated is an anonymous class. Then:
If T denotes a class, then an anonymous direct subclass of the class named by T is declared. It is a compile-time error if the
class denoted by T is a final class.
If T denotes an interface, then an anonymous direct subclass of Object that implements the interface named by T is declared.
In either case, the body of the subclass is the ClassBody given in the class instance creation expression.
The class being instantiated is the anonymous subclass.
Emphasis mine.
Also, in JLS - Section # 12.5, you can read about the Object Creation Process. I'll quote one statement from that here: -
Whenever a new class instance is created, memory space is allocated
for it with room for all the instance variables declared in the class
type and all the instance variables declared in each superclass of the
class type, including all the instance variables that may be hidden.
Just before a reference to the newly created object is returned as the
result, the indicated constructor is processed to initialize the new
object using the following procedure:
You can read about the complete procedure on the link I provided.
To practically see that the class being instantiated is an Anonymous SubClass, you just need to compile both your classes. Suppose you put those classes in two different files:
My.java:
abstract class My {
public void myMethod() {
System.out.print("Abstract");
}
}
Poly.java:
class Poly extends My {
public static void main(String a[]) {
My m = new My() {};
m.myMethod();
}
}
Now, compile both your source files:
javac My.java Poly.java
Now in the directory where you compiled the source code, you will see the following class files:
My.class
Poly$1.class // Class file corresponding to anonymous subclass
Poly.class
See that class - Poly$1.class. It's the class file created by the compiler corresponding to the anonymous subclass you instantiated using the below code:
new My() {};
So, it's clear that there is a different class being instantiated. It's just that, that class is given a name only after compilation by the compiler.
In general, all the anonymous subclasses in your class will be named in this fashion:
Poly$1.class, Poly$2.class, Poly$3.class, ... so on
Those numbers denote the order in which those anonymous classes appear in the enclosing class.
The above instantiates an anonymous inner class which is a subclass of the my abstract class. It's not strictly equivalent to instantiating the abstract class itself. OTOH, every subclass instance is an instance of all its super classes and interfaces, so most abstract classes are indeed instantiated by instantiating one of their concrete subclasses.
If the interviewer just said "wrong!" without explaining, and gave this example, as a unique counterexample, I think he doesn't know what he's talking about, though.
= my() {}; means that there's an anonymous implementation, not simple instantiation of an object, which should have been : = my(). You can never instantiate an abstract class.
Just observations you could make:
Why poly extends my? This is useless...
What is the result of the compilation? Three files: my.class, poly.class and poly$1.class
If we can instantiate an abstract class like that, we can instantiate an interface too... weird...
Can we instantiate an abstract class?
No, we can't. What we can do is, create an anonymous class (that's the third file) and instantiate it.
What about a super class instantiation?
The abstract super class is not instantiated by us but by java.
EDIT: Ask him to test this
public static final void main(final String[] args) {
final my m1 = new my() {
};
final my m2 = new my() {
};
System.out.println(m1 == m2);
System.out.println(m1.getClass().toString());
System.out.println(m2.getClass().toString());
}
output is:
false
class my$1
class my$2
You can simply answers, in just one line
No, you can never instance Abstract Class
But, interviewer still not agree, then you can tell him/her
all you can do is, you can create an Anonymous Class.
And, according to Anonymous class, class declared and instantiate at the same place/line
So, it might be possible that, interviewer would be interested to check your confidence level and how much you know about the OOPs .
The technical part has been well-covered in the other answers, and it mainly ends in:
"He is wrong, he doesn't know stuff, ask him to join SO and get it all cleared :)"
I would like to address the fact(which has been mentioned in other answers) that this might be a stress-question and is an important tool for many interviewers to know more about you and how do you react to difficult and unusual situations. By giving you incorrect codes, he probably wanted to see if you argued back. To know whether you have the confidence to stand up against your seniors in situations similar to this.
P.S: I don't know why but I have a feeling that the interviewer has read this post.
Abstract classes cannot be instantiated, but they can be subclassed. See This Link
The best example is
Although Calender class has a abstract method getInstance(), but when you say Calendar calc=Calendar.getInstance();
calc is referring to the class instance of class GregorianCalendar as "GregorianCalendar extends Calendar "
Infact annonymous inner type allows you to create a no-name subclass of the abstract class and an instance of this.
Technical Answer
Abstract classes cannot be instantiated - this is by definition and design.
From the JLS, Chapter 8. Classes:
A named class may be declared abstract (§8.1.1.1) and must be declared
abstract if it is incompletely implemented; such a class cannot be
instantiated, but can be extended by subclasses.
From JSE 6 java doc for Classes.newInstance():
InstantiationException - if this Class represents an abstract class, an interface, an array
class, a primitive type, or void; or if the class has no nullary constructor; or if the
instantiation fails for some other reason.
You can, of course, instantiate a concrete subclass of an abstract class (including an anonymous subclass) and also carry out a typecast of an object reference to an abstract type.
A Different Angle On This - Teamplay & Social Intelligence:
This sort of technical misunderstanding happens frequently in the real world when we deal with complex technologies and legalistic specifications.
"People Skills" can be more important here than "Technical Skills". If competitively and aggressively trying to prove your side of the argument, then you could be theoretically right, but you could also do more damage in having a fight / damaging "face" / creating an enemy than it is worth. Be reconciliatory and understanding in resolving your differences. Who knows - maybe you're "both right" but working off slightly different meanings for terms??
Who knows - though not likely, it is possible the interviewer deliberately introduced a small conflict/misunderstanding to put you into a challenging situation and see how you behave emotionally and socially. Be gracious and constructive with colleagues, follow advice from seniors, and follow through after the interview to resolve any challenge/misunderstanding - via email or phone call. Shows you're motivated and detail-oriented.
It is a well-established fact that abstract class can not be instantiated as everyone answered.
When the program defines anonymous class, the compiler actually creates a new class with different name (has the pattern EnclosedClassName$n where n is the anonymous class number)
So if you decompile this Java class you will find the code as below:
my.class
abstract class my {
public void mymethod()
{
System.out.print("Abstract");
}
}
poly$1.class (the generated class of the "anonymous class")
class poly$1 extends my
{
}
ploly.cass
public class poly extends my
{
public static void main(String[] a)
{
my m = new poly.1(); // instance of poly.1 class NOT the abstract my class
m.mymethod();
}
}
About Abstract Classes
Cannot create object of an abstract class
Can create variables (can behave like datatypes)
If a child can not override at least of one abstract method of the parent, then child also becomes abstract
Abstract classes are useless without child classes
The purpose of an abstract class is to behave like a base. In inheritance hierarchy you will see abstract classes towards the top.
No, you can't instantite an abstract class.We instantiate only anonymous class.In abstract class we declare abstract methods and define concrete methods only.
Extending a class doesn't mean that you are instantiating the class. Actually, in your case you are creating an instance of the subclass.
I am pretty sure that abstract classes do not allow initiating. So, I'd say no: you can't instantiate an abstract class. But, you can extend it / inherit it.
You can't directly instantiate an abstract class. But it doesn't mean that you can't get an instance of class (not actully an instance of original abstract class) indirectly. I mean you can not instantiate the orginial abstract class, but you can:
Create an empty class
Inherit it from abstract class
Instantiate the dervied class
So you get access to all the methods and properties in an abstract class via the derived class instance.
It's impossible to instantiate an abstract class.
What you really can do, has implement some common methods in an abstract class and let others unimplemented (declaring them abstract) and let the concrete descender implement them depending on their needs.
Then you can make a factory, which returns an instance of this abstract class (actually his implementer). In the factory you then decide, which implementer to choose. This is known as a factory design pattern:
public abstract class AbstractGridManager {
private LifecicleAlgorithmIntrface lifecicleAlgorithm;
// ... more private fields
//Method implemented in concrete Manager implementors
abstract public Grid initGrid();
//Methods common to all implementors
public Grid calculateNextLifecicle(Grid grid){
return this.getLifecicleAlgorithm().calculateNextLifecicle(grid);
}
public LifecicleAlgorithmIntrface getLifecicleAlgorithm() {
return lifecicleAlgorithm;
}
public void setLifecicleAlgorithm(LifecicleAlgorithmIntrface lifecicleAlgorithm) {
this.lifecicleAlgorithm = lifecicleAlgorithm;
}
// ... more common logic and getters-setters pairs
}
The concrete implementer only needs to implement the methods declared as abstract, but will have access to the logic implemented in those classes in an abstract class, which are not declared abstract:
public class FileInputGridManager extends AbstractGridManager {
private String filePath;
//Method implemented in concrete Manager implementors
abstract public Grid initGrid();
public class FileInputGridManager extends AbstractGridManager {
private String filePath;
//Method implemented in concrete Manager implementors
abstract public Grid initGrid();
public Grid initGrid(String filePath) {
List<Cell> cells = new ArrayList<>();
char[] chars;
File file = new File(filePath); // for example foo.txt
// ... more logic
return grid;
}
}
Then finally the factory looks something like this:
public class GridManagerFactory {
public static AbstractGridManager getGridManager(LifecicleAlgorithmIntrface lifecicleAlgorithm, String... args){
AbstractGridManager manager = null;
// input from the command line
if(args.length == 2){
CommandLineGridManager clManager = new CommandLineGridManager();
clManager.setWidth(Integer.parseInt(args[0]));
clManager.setHeight(Integer.parseInt(args[1]));
// possibly more configuration logic
...
manager = clManager;
}
// input from the file
else if(args.length == 1){
FileInputGridManager fiManager = new FileInputGridManager();
fiManager.setFilePath(args[0]);
// possibly more method calls from abstract class
...
manager = fiManager ;
}
//... more possible concrete implementors
else{
manager = new CommandLineGridManager();
}
manager.setLifecicleAlgorithm(lifecicleAlgorithm);
return manager;
}
}
The receiver of AbstractGridManager would call the methods on him and get the logic, implemented in the concrete descender (and partially in the abstract class methods) without knowing what is the concrete implementation he got. This is also known as inversion of control or dependency injection.
You can say: we can't instantiate an abstract class, but we can use new keyword to create an anonymous class instance by just adding {} as implement body at the the end of the abstract class.
No, we can't create the object of abstract class, but create the reference variable of the abstract class. The reference variable is used to refer to the objects of derived classes (Sub classes of Abstract class)
Here is the example that illustrates this concept
abstract class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
// area is now an abstract method
abstract double area();
}
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
}
// override area for rectangle
double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Figure {
Triangle(double a, double b) {
super(a, b);
}
// override area for right triangle
double area() {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
class AbstractAreas {
public static void main(String args[]) {
// Figure f = new Figure(10, 10); // illegal now
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref; // this is OK, no object is created
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
}
}
Here we see that we cannot create the object of type Figure but we can create a reference variable of type Figure. Here we created a reference variable of type Figure and Figure Class reference variable is used to refer to the objects of Class Rectangle and Triangle.
Actually we can not create an object of an abstract class directly. What we create is a reference variable of an abstract call. The reference variable is used to Refer to the object of the class which inherits the Abstract class i.e. the subclass of the abstract class.

Categories

Resources