Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Use of constructor in abstract 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 "Use of constructor in abstract class? " Watch "Use of constructor in abstract class? " New topic
Author

Use of constructor in abstract class?

Ja vardhan
Ranch Hand

Joined: May 09, 2005
Posts: 169
Hi,

I have few doubts regarding abstract classes.

1. What is the use of having constructor in abstract class? Any how we cant create instance on abstract class. so whats the use of constructor?

2. When we are not able to create instance of abstract class, whats the use of having concrete methods(fully coded) in abstarct class? How can we call them without an instance?

Pls clarify.

Thanks.


Javardhan:
Anupam Sinha
Ranch Hand

Joined: Apr 13, 2003
Posts: 1088
Let say you have a class named car. It different methods like

drive() { // method code goes here }
abstract absImplemented();
abstract safetyFeatures();

etc..

A car may implement the ABS and other safety feature but whatever it may use it would drive. So when let say Honda class implements it. It would not have to rewrite the method implementation to how to drive it(assuming it is the same for all the car). It is basically there so that you can put things that you think are common to all subclasses.
Kj Reddy
Ranch Hand

Joined: Sep 20, 2003
Posts: 1704
If you implement a method or consturctor they can be reused from sub classes which extends the abastract class.
[ March 20, 2006: Message edited by: KJ Reddy ]
Ja vardhan
Ranch Hand

Joined: May 09, 2005
Posts: 169
Anupam,

I am sorry, I didnt understand your code, pls explain in detail.

Thanks.
Arul Prasad
Ranch Hand

Joined: Jan 20, 2005
Posts: 57
hi see the code snippet below



So in my code TestEngine is an abstract having a constructor to initiate its two members

and the JavaTestEngine is a sub class of my abstract TestEngine which inheriting the two variables of the parent class

hope u Got why we need a constructor for the abstract class.
Note

All abstract class are not pure abstract, partially they are . So if u need a pure abstract class Go for an Interface.

In java all classes having a constructor (default)

U can call the Test Engine like ....


[ March 20, 2006: Message edited by: Arul Prasad ]

With Regards<br />Arul
Aleksander Zielinski
Ranch Hand

Joined: Nov 11, 2005
Posts: 127
Originally posted by KJ Reddy:
All constructors and methods are getting inherited in sub classes.


Subclass does not inherit superclass' constructor.
Kj Reddy
Ranch Hand

Joined: Sep 20, 2003
Posts: 1704
Originally posted by Aleksander Zielinski:


Subclass does not inherit superclass' constructor.


Thanks for correcting me, I edited my post.
Roopa Chitradurga
Greenhorn

Joined: Mar 17, 2006
Posts: 8
"1. What is the use of having constructor in abstract class? Any how we cant create instance on abstract class. so whats the use of constructor?"

The purpose of abstract class is to provide common information for the subclasses.The abstract classes cannot be instantiated.You will get a compile error.


"2. When we are not able to create instance of abstract class, whats the use of having concrete methods(fully coded) in abstarct class? How can we call them without an instance? "


An abstract class can have methods with full body apart and abstract method.
This is especially usefull when extending classes.Say,you have an super class Animal and sub-classes Dog,Cat,Cow etc.All the different type of animals have one thing comon.ie,sound.So the Animal class has methods to define these sub-classes and also a method called sound().Though this method does nothing.It is only used in subclasses and implemented.It is just declared in Animal class but not defined.

See the code below:

public abstract class Animal{
public abstract void sound();

private String type;

public Animal(String atype){
type=new String(atype);
}
public String toString(){
return "This is a "+ type;
}
}

public class Dog extends Animal{
public Dog(String aname){
super("Dog");
this.aname=aname;
}
public void sound(){
System.out.println("woof woof");
}
}

similarly you can do for cat,cow etc.

This is known as polymorphisim.The advantage is that the single method can behave differently,depending on the type of object it is called.


Thanks,
Roopa
Ja vardhan
Ranch Hand

Joined: May 09, 2005
Posts: 169
Thanks for your replies.

One more doubt regarding constructors:

From K&B book I read
-----------------------------------------------------------------------
If you do type your own constructor (as opposed to relying on compiler generated default constructor), and you do not type in the call to super(), the compiler will insert a no-arg call to super() for you.
-----------------------------------------------------------------------

Whats the case if I dont have no-arg constructor in the super class??

Why it shouldn't throw error when compiler is insertign call to super class's no-arg constructor but actually I dont have such constructor?

Thanks.
Higgledy Smith
Ranch Hand

Joined: Mar 07, 2006
Posts: 192
Originally posted by Ja vardhan:
Thanks for your replies.

One more doubt regarding constructors:

From K&B book I read
-----------------------------------------------------------------------
If you do type your own constructor (as opposed to relying on compiler generated default constructor), and you do not type in the call to super(), the compiler will insert a no-arg call to super() for you.
-----------------------------------------------------------------------

Whats the case if I dont have no-arg constructor in the super class??

Why it shouldn't throw error when compiler is insertign call to super class's no-arg constructor but actually I dont have such constructor?

Thanks.


If you do not define any constructor in the super class the compiler will generate a no-arg constructor in the super class.

If in the super class you do define a constructor that takes args the compiler will STILL automatically generate a no-arg constructor in the super class.
Ene Crus
Greenhorn

Joined: Mar 19, 2006
Posts: 8
Originally posted by Higgledy Smith:

If in the super class you do define a constructor that takes args the compiler will STILL automatically generate a no-arg constructor in the super class.


I think this is how it works.
When you don't define a constructor at all, compiler generates automatically a no-arg constructor

When you define a constructor with arg, compiler wouldnt generate automatically a no-arg constructor. Meaning, when you ONLY define a constructor with arguments and you want to use constructor without args, you cant use a constructor without args... You must define separately by doing

//without this you cant use a no-args constructor... well
//unless you get rid of the with-args constructor and let the
//compiler automatically generate the no-args.
SuperClass(){
}

SuperClass(args) {
}


cheers,
euio
mi te
Greenhorn

Joined: Mar 09, 2006
Posts: 29
Thanks EUIO. I was just trying out what Higgledy Smith was saying about with-args constructor and it didnt compile.

class With_args{
With_args(int i){}
}

class Main{
public static void main(String args[]){
With_args wa = new With_args();
}
}

This wont compile.
Higgledy Smith
Ranch Hand

Joined: Mar 07, 2006
Posts: 192
Now I am tripping. This compiles and runs for me:

class Super {
int index = 5;
public void Super(int i){
index = i;
}
public void printVal() {
System.out.println( "Super" );
}
}

class Sub extends Super {
int index = 2;

public void printVal() {
System.out.println( "Sub" );
}
}

public class Runner {
public static void main( String argv[] )
{
Super sup = new Super();
Sub subby = new Sub();
System.out.print( sup.index + "," );
sup.printVal();
subby.printVal();
}
}
M Anderson
Greenhorn

Joined: Mar 17, 2006
Posts: 25
this method:

public void Super(int i) {...} is not a constructor. It's a method called 'Super' that takes an int as an arg. Therefore, the compiler has given you the default no-arg constructor and is why your code is compiling.

The constructor won't have a return.

Like this:

public Super(int i) {...}


Mike -- SCJP, SCWCD
Ja vardhan
Ranch Hand

Joined: May 09, 2005
Posts: 169
One more doubt regarding constructors:

From K&B book I read
-----------------------------------------------------------------------
If you do type your own constructor (as opposed to relying on compiler generated default constructor), and you do not type in the call to super(), the compiler will insert a no-arg call to super() for you.
-----------------------------------------------------------------------

Whats the case if I dont have no-arg constructor in the super class??

Why it shouldn't throw error when compiler is insertign call to super class's no-arg constructor but actually I dont have such constructor?

Thanks.
--------------------

Javardhan:



Hey sorry friends, actually its throwing error in this case, earlier it was not throwing error because of a funny mistake: I didnt extend the super class at all

In our explicitly typed constructor, if we dont have call to super class constructor and when we dont have no-arg constructor in super class: the compiler will definitely generates error.

Thanks.
Sandeep Vaid
Ranch Hand

Joined: Feb 27, 2006
Posts: 390
The answer to "What's the use of constructor in abstract class" is
Though we can't create an instance of abstract class we can utilise it's constructor in constructor of it's subclass.....


[ March 21, 2006: Message edited by: Sandeeep Vaid ]
Durga Krishna
Greenhorn

Joined: Apr 05, 2007
Posts: 28
I have one more doubt.....
I can have an abstract class without having any abstract methods in it.
Then what is the use with such a class declaring as abstract.?What i mean is - why compiler will not throw any exception if, we compile an abstract class having no abstract methods in that class?
Cor Takken
Ranch Hand

Joined: May 21, 2007
Posts: 58
Originally posted by Durga Krishna:
I have one more doubt.....
I can have an abstract class without having any abstract methods in it.
Then what is the use with such a class declaring as abstract.?What i mean is - why compiler will not throw any exception if, we compile an abstract class having no abstract methods in that class?


Though the class is completely filled with concrete methods, the class may still be extending another abstract class or define that an interface is implemented without actually implementing the methods of the interface. Your question is good. In my opinion it allows for design decisions which need this constructions. I think..

But then again: I might be wrong... :roll:

Cor


SCJP 1.5
Dolphins are grey, but they dream in colour.
Raghavan Muthu
Ranch Hand

Joined: Apr 20, 2006
Posts: 3344


Originally posted by Durga Krishna:
I have one more doubt.....
I can have an abstract class without having any abstract methods in it.
Then what is the use with such a class declaring as abstract.?What i mean is - why compiler will not throw any exception if, we compile an abstract class having no abstract methods in that class?


As Cor told, probably a design decision. May be in future, it can very well have some abstract methods but not at present. But if you dont declare the class as abstract just because it does not contain any abstract methods and then later you change it to abstract once it has some abstract methods, the impact would be much more as you may need to do a lot of rework to change the usage of this class accordingly.

One point of the impact and change would be removing the instance creation of this class as its abstract now

HtH.


Everything has got its own deadline including one's EGO!
[CodeBarn] [Java Concepts-easily] [Corey's articles] [SCJP-SUN] [Servlet Examples] [Java Beginners FAQ] [Sun-Java Tutorials] [Java Coding Guidelines]
gaurav Taneja
Greenhorn

Joined: May 30, 2008
Posts: 5
Hi Friends ,
In java thumb rule is every object extends Obect class,means we cannot create object without extending Object Class,every class implictly extends Object class including abstract class. So without having default constructors we cannot call Object class constructor. As you know that compiler creates default constructor when there is no constructor that means abstract class have constructors.So you are clear why abstract class have constructors
Steven Elliott
Greenhorn

Joined: Mar 28, 2002
Posts: 14
I had to reply to this to clarify what seems to be a misunderstanding regarding abstract classes and constructors and whether or not an abstract class can be instantiated.

The contract of an abstract class is that the first concrete class must implement all abstract methods. In fact the abstract class itself can do this and by providing a concrete implementation of the abstract method(s) when instantiated.

Here is a really simple example:


The Test instance reference in AbstractTest is instantiated using new Test() and provides the concrete implementation of getI(). The compiles and runs returning:
test 1 = 10

What is interesting is if you add the following to the main method:
System.out.println("Test classname = "+at.test.getClass().getName());

will return "Test classname = classes.AbstractTest$1" indicating that Test has been compiled as an inner class of AbstractTest...! What kind of inner class?

What is then interesting is if you test instanceof:
System.out.println("at.test instanceof Test = "+(at.test instanceof Test));

Will return "Test instanceof Test = true"

The answer is yes, you can instantiate an abstract class... more or less;)

dennis deems
Ranch Hand

Joined: Mar 12, 2011
Posts: 808
Steven Elliott wrote:What is interesting is if you add the following to the main method:
System.out.println("Test classname = "+at.test.getClass().getName());
will return "Test classname = classes.AbstractTest$1" indicating that Test has been compiled as an inner class of AbstractTest...! What kind of inner class?

An anonymous subtype of Test.


What is then interesting is if you test instanceof:
System.out.println("at.test instanceof Test = "+(at.test instanceof Test));

Will return "Test instanceof Test = true"

The answer is yes, you can instantiate an abstract class... more or less;)


Technically, what you can instantiate is an anonymous subclass of an abstract class, not the abstract class itself. That's why the Class.getName returns a strange value, and not "Test". You must provide the definition of the subtype, including required implementations, "Just-In-Time". The instanceof expression evaluates to true because a subtype of classX IS-A classX.
Steven Elliott
Greenhorn

Joined: Mar 28, 2002
Posts: 14
An anonymous subtype of Test.


Yeah. Expands the general understanding of where you might find an anonymous inner class but a common enough usage to find as a parameter.

I would be surprised if something like this appeared on the test but it might get asked at an interview.
Andrew flexdeveloper
Greenhorn

Joined: Aug 04, 2011
Posts: 7
constructor can not be created in an abstract class.even though we write the constructor, when the constructor will be called..?only if the object is created. but we cannot create an object of abstract class.even though we create object using indirect way, there also, we cannot call the constructor of the abstract class.finally, constructor for the abstract class cannot be called.


Flex Development | Flex Developer in India
Randall Twede
Ranch Hand

Joined: Oct 21, 2000
Posts: 4339
    
    2

this post already got answered well, but i just wanted to say i love abstract classes when you can use them. you can implement all the methods if you want to, and sub-classes inherit these methods. its especially handy when you implement a lot of interfaces and only want to rewrite one or two methods. you can make abstract class that has "do nothing" methods. makes the real code more readable. anyway, just my 2 cents worth


SCJP
Visit my download page
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Use of constructor in abstract class?
 
Similar Threads
abstarct class can have constructor?
abstract class
how abstract class constructor invokes while creating instance of Subclass
Static methods
doubt in abstract class