Can an abstract class have a constructor? - java

Can an abstract class have a constructor?
If so, how can it be used and for what purposes?

Yes, an abstract class can have a constructor. Consider this:
abstract class Product {
int multiplyBy;
public Product( int multiplyBy ) {
this.multiplyBy = multiplyBy;
}
public int mutiply(int val) {
return multiplyBy * val;
}
}
class TimesTwo extends Product {
public TimesTwo() {
super(2);
}
}
class TimesWhat extends Product {
public TimesWhat(int what) {
super(what);
}
}
The superclass Product is abstract and has a constructor. The concrete class TimesTwo has a constructor that just hardcodes the value 2. The concrete class TimesWhat has a constructor that allows the caller to specify the value.
Abstract constructors will frequently be used to enforce class constraints or invariants such as the minimum fields required to setup the class.
NOTE: As there is no default (or no-arg) constructor in the parent
abstract class, the constructor used in subclass must explicitly call
the parent constructor.

You would define a constructor in an abstract class if you are in one of these situations:
you want to perform some
initialization (to fields of the
abstract class) before the
instantiation of a subclass actually
takes place
you have defined final fields in the
abstract class but you did not
initialize them in the declaration
itself; in this case, you MUST have
a constructor to initialize these
fields
Note that:
you may define more than one
constructor (with different
arguments)
you can (should?) define all your
constructors protected (making them
public is pointless anyway)
your subclass constructor(s) can
call one constructor of the abstract
class; it may even have to call it
(if there is no no-arg constructor
in the abstract class)
In any case, don't forget that if you don't define a constructor, then the compiler will automatically generate one for you (this one is public, has no argument, and does nothing).

Yes it can have a constructor and it is defined and behaves just like any other class's constructor. Except that abstract classes can't be directly instantiated, only extended, so the use is therefore always from a subclass's constructor.

Yes! Abstract classes can have constructors!
Yes, when we define a class to be an Abstract Class it cannot be instantiated but that does not mean an Abstract class cannot have a constructor. Each abstract class must have a concrete subclass which will implement the abstract methods of that abstract class.
When we create an object of any subclass all the constructors in the corresponding inheritance tree are invoked in the top to bottom approach. The same case applies to abstract classes. Though we cannot create an object of an abstract class, when we create an object of a class which is concrete and subclass of the abstract class, the constructor of the abstract class is automatically invoked. Hence we can have a constructor in abstract classes.
Note: A non-abstract class cannot have abstract methods but an abstract class can have a non-abstract method. Reason is similar to that of constructors, difference being instead of getting invoked automatically we can call super(). Also, there is nothing like an abstract constructor as it makes no sense at all.

Not only can it, it always does. If you do not specify one then it has a default no arg constructor, just like any other class. In fact, ALL classes, including nested and anonymous classes, will get a default constructor if one is not specified (in the case of anonymous classes it is impossible to specify one, so you will always get the default constructor).
A good example of an abstract class having a constructor is the Calendar class. You get a Calendar object by calling Calendar.getInstance(), but it also has constructors which are protected. The reason its constructors are protected is so that only its subclasses can call them (or classes in the same package, but since it's abstract, that doesn't apply). GregorianCalendar is an example of a class that extends Calendar.

Although there are many good answers, I would like to give my 2 cents.
Constructor DOES NOT BUILD THE OBJECT. It is used to initialize an object.
Yes, an Abstract class always has a constructor. If you do not define your own constructor, the compiler will give a default constructor to the Abstract class.
Above holds true for all classes - nested, abstract, anonymous, etc.
An abstract class (unlike interface) can have non-final non-static fields which need initialization. You can write your own constructor in the abstract class to do that. But, in that case, there won't be any default constructor.
public abstract class Abs{
int i;
int j;
public Abs(int i,int j){
this.i = i;
this.j = j;
System.out.println(i+" "+j);
}
}
Be careful while extending above abstract class, you have to explicitly call super from each constructor. The first line of any constructor calls to super(). if you do not explicitly call super(), Java will do that for you.
Below code will not compile:
public class Imp extends Abs{
public Imp(int i, int j,int k, int l){
System.out.println("2 arg");
}
}
You have to use it like below example:
public class Imp extends Abs{
public Imp(int i, int j,int k, int l){
super(i,j);
System.out.println("2 arg");
}
}

An abstract class can have a constructor BUT you can not create an object of abstract class so how do you use that constructor?
Thing is when you inherit that abstract class in your subclass you can pass values to its(abstract's) constructor through super(value) method in your subclass and no you don't inherit a constructor.
so using super you can pass values in a constructor of the abstract class and as far as I remember it has to be the first statement in your method or constructor.

Yes it can, abstract classes constructors are generally used for super calls for initialization events common to all the subclasses

Of Course, abstract class can have a constructor.Generally class constructor is used to initialise fields.So, an abstract class constructor is used to initialise fields of the abstract class. You would provide a constructor for an abstract class if you want to initialise certain fields of the abstract class before the instantiation of a child-class takes place. An abstract class constructor can also be used to execute code that is relevant for every child class. This prevents code duplication.
We cannot create an instance of an abstract class,But we can create instances of classes those are derived from the abstract class. So, when an instance of derived class is created, the parent abstract class constructor is automatically called.
Reference :This Article

Yes, Abstract Classes can have constructors !
Here is an example using constructor in abstract class:
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());
}
}
So I think you got the answer.

As described by javafuns here, this is an example:
public abstract class TestEngine
{
private String engineId;
private String engineName;
public TestEngine(String engineId , String engineName)
{
this.engineId = engineId;
this.engineName = engineName;
}
//public gettors and settors
public abstract void scheduleTest();
}
public class JavaTestEngine extends TestEngine
{
private String typeName;
public JavaTestEngine(String engineId , String engineName , String typeName)
{
super(engineId , engineName);
this.typeName = typeName;
}
public void scheduleTest()
{
//do Stuff
}
}

In a concrete class, declaration of a constructor for a concrete type Fnord effectively exposes two things:
A means by which code can request the creation of an instance of Fnord
A means by which an instance of a type derived from Fnord which is under construction can request that all base-class features be initialized.
While there should perhaps be a means by which these two abilities could be controlled separately, for every concrete type one definition will enable both. Although the first ability is not meaningful for an abstract class, the second ability is just as meaningful for an abstract class as it would be for any other, and thus its declaration is just as necessary and useful.

Abstract class can have a constructor though it cannot be instantiated. But the constructor defined in an abstract class can be used for instantiation of concrete class of this abstract class. Check JLS:
It is a compile-time error if an attempt is made to create an instance of an abstract class using a class instance creation
expression.
A subclass of an abstract class that is not itself abstract may be
instantiated, resulting in the execution of a constructor for the
abstract class and, therefore, the execution of the field initializers
for instance variables of that class.

yes it is. And a constructor of abstract class is called when an instance of a inherited class is created. For example, the following is a valid Java program.
// An abstract class with constructor
abstract class Base {
Base() { System.out.println("Base Constructor Called"); }
abstract void fun();
}
class Derived extends Base {
Derived() { System.out.println("Derived Constructor Called"); }
void fun() { System.out.println("Derived fun() called"); }
}
class Main {
public static void main(String args[]) {
Derived d = new Derived();
}
}
This is the output of the above code,
Base Constructor Called
Derived Constructor Called
references:
enter link description here

Consider this:
abstract class Product {
int value;
public Product( int val ) {
value= val;
}
abstract public int multiply();
}
class TimesTwo extends Product {
public int mutiply() {
return value * 2;
}
}
The superclass is abstract and has a constructor.

Yes surely you can add one, as already mentioned for initialization of Abstract class variables.
BUT if you dont explicitly declare one, it anyways has an implicit constructor for "Constructor Chaining" to work.

Since an abstract class can have variables of all access modifiers, they have to be initialized to default values, so constructor is necessary.
As you instantiate the child class, a constructor of an abstract class is invoked and variables are initialized.
On the contrary, an interface does contain only constant variables means they are already initialized. So interface doesn't need a constructor.

In order to achieve constructor chaining, the abstract class will have a constructor.
The compiler keeps Super() statement inside the subclass constructor, which will call the superclass constructor. If there were no constructors for abstract classes then java rules are violated and we can't achieve constructor chaining.

Yes, an Abstract Class can have a Constructor. You Can Overload as many Constructor as you want in an Abstract Class. These Contractors Can be used to Initialized the initial state of the Objects Extending the Abstract Class. As we know we can't make an object of an Abstract Class because Objects are Created by the "new" keywords and not by the constructors...they are there for only initializing the state of the subclass Objects.

The purpose of the constructor in a class is used to initialize fields but not to "build objects". When you try to create a new instance of an abstract SuperClass, the compiler will give you an error. However, we can inherit an abstract class Employee and make use of its constructor by setting its variables See example below
public abstract class Employee {
private String EmpName;
abstract double calcSalary();
Employee(String name) {
this.EmpName = name;// constructor of abstract class super class
}
}
class Manager extends Employee{
Manager(String name) {
super(name);// setting the name in the constructor of sub class
}
double calcSalary() {
return 0;
}
}

package Test1;
public class AbstractClassConstructor {
public AbstractClassConstructor() {
}
public static void main(String args[]) {
Demo obj = new Test("Test of code has started");
obj.test1();
}
}
abstract class Demo{
protected final String demoValue;
public Demo(String testName){
this.demoValue = testName;
}
public abstract boolean test1();
}
class Test extends Demo{
public Test(String name){
super(name);
}
#Override
public boolean test1() {
System.out.println( this.demoValue + " Demo test started");
return true;
}
}

Yes..It is like any other class. It can have a constructor and it is called after creating object for the base class.

Related

Call constructor in an abstract class

Is it possible to call a constructor in a abstract class?
I read that this constructor can be called through one of its non-abstract subclasses. But I don't understand that statement. Can anybody explain this with an example?
You can define a constructor in an abstract class, but you can't construct that object. However, concrete sub-classes can (and must) call one of the constructors defined in the abstract parent class.
Consider the following code example:
public abstract class Test {
// abstract class constructor
public Test() {
System.out.println("foo");
}
// concrete sub class
public static class SubTest extends Test {
// no constructor defined, but implicitly calls no-arg constructor
// from parent class
}
public static void main(String[] args) throws Exception {
Test foo = new Test(); // Not allowed (compiler error)
SubTest bar = new SubTest(); // allowed, prints "foo"
}
}
You can't call an abstract class constructor with a class instance creation expression, i.e.
// Invalid
AbstractClass x = new AbstractClass(...);
However, in constructing an object you always go through the constructors of the whole inheritance hierarchy. So a constructor from a subclass can call the constructor of its abstract superclass using super(...). For example:
public class Abstract {
protected Abstract(int x) {
}
}
public class Concrete {
public Concrete(int x, int y) {
super(x); // Call the superclass constructor
}
}
As constructors of abstract classes can only be called within subclass constructors (and by chaining one to another within the same class), I typically make them protected... making them public would serve no purpose.
The normal rules apply if you don't specify a super(...) or this(...) call in a concrete subclass constructor - it's equivalent to a super(); statement at the start of a constructor, calling a parameterless constructor in the superclass... so there'd have to be such a constructor.
In this example Java program, we have an abstract class Servidor, which has one parametric constructor, which accepts name. Subclass provides that name to superclass while creating concrete instance of Servidor and overriding abstract method start(). Since this program compile and run fine you can definitely say abstract class can have constructors in Java.
public class AbstractConstructorTest {
public static void main(String args[]) {
Servidor Servidor = new Tomcat("Apache Tomcat");
Servidor.start();
}
}
abstract class Servidor{
protected final String name;
public Servidor(String name){
this.name = name;
}
public abstract boolean start();
}
class Tomcat extends Servidor{
public Tomcat(String name){
super(name);
}
#Override
public boolean start() {
System.out.println( this.name + " started successfully");
return true;
}
}
Output:
Apache Tomcat started successfully
You can obviously do something like:
public class ConcreteClass extends AbstractClass {
public ConcreteClass(){ // concrete class constructor
super(); // abstract class constructor
}
}
A constructor of an abstract class can be used only inside constructors of concrete classes inheriting from it.
Abstract and Concrete classes are something like Generalization and Specialization in Java and can be executed using inheritance. Let me explain with a plain and simple example. Say we have a class "DBConnector". It seems to be more generalized class and its meaning less to instantiate the class (which DB you are connecting to, driver vary for each DB right). Hence we can make DBConnector as abstract. That is the reason why we cannot basically instantiate Abstract classes.
Now we can create different concrete classes for each database extending the behavior of our concrete class like "OracelDBConnector", "MySQLDBConnector" etc., As we inherit the properties of abstract class into concrete class, we initialize the abstract class properties ideally using abstract class constructor using concrete class constructor using super(parameter list).
Thanks,
JK

abstract class with default constructor and class with private constructor difference

what's the difference between an Abstract class with a default constructor and a class with private constructor?
I also have another doubt ,
consider this program below. Can anyone please explain me.Does such code have any use ?
abstract class AbstractAndPrivate
{
AbstractAndPrivate()
{
AbstractAndPrivate ref= new AbstractAndPrivate(1) {
#Override
int m2() {
// TODO Auto-generated method stub
return 0;
}
};
}
void m1()
{
System.out.println("m1() accessed");
}
abstract int m2();
AbstractAndPrivate(int a)
{
}
public static void main(String[] args) {
System.out.print("hello ");
AbstractAndPrivate ref= new AbstractAndPrivate() {public int m2(){return 1;}};
System.out.println(ref);
ref.m1();
ref.m2();
}
}
what's the difference between an Abstract class with a default constructor and a class with private constructor?
If there's a default constructor, it will be callable from subclasses. If it's private, you'll only be able to create subclasses within the same class, as that's the only context in which the private constructor will be accessible.
Note that the code you've provided is neither of these situations - it's explicitly providing a package-protected parameterless constructor. That's not private, and it's not a default constructor.
Whether the class is abstract or not is orthogonal to the constructors it provides, although an abstract class with only a private constructor forces you to create subclasses within the declaring class in order to create instances, rather than just relying on you creating instances within the declaring class.
also, abstract class can have an abstract method, that needs to be implemented by subclasses (unless they're abstract too)
EDIT: -1? come on, abstract methods are also sort of explains the logical difference between abstract classes and classes with private constructor. please...

How to force subclasses to set a variable in java?

I have a class which defines all of the basic parameters for a given screen. From here every screen in the application is a subclass of this. I need every screen (i.e. subclass) to set the value of a variable in its implementation (namely, each screen must define what level it is in a navigation tree).
Also, ideally, this variable should be final when it is set in the sub classes (I realise this probably isn't possible).
What is the best way to go about this? Is there a way to correctly enforce this type of behaviour in Java?
#pst's comment lead to this solution.
This can't be done with a variable. But an abstract class can require that a particular method is implemented: this method could return the applicable value
From declaring an abstract function to set or return the variable, you can force any subclass to implement it correctly.
Next, the function must be called by every single subclass of the outer class. This implies that it must be done somewhere in the outer class. This can be done in the no-argument constructor of the outer class without having to worry about subclasses calling super:
Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.
(Java docs: Super)
Based on that, this solution will hold up and correctly force the variable to be set as long as either:
No other constructor is created in the superclass (hence super can't be used in a subclass to call a different constructor instead)
All other constructors in the superclass still call the default constructor internally
The code:
Superclass:
public abstract class SuperClass {
// Variable all inner classes must set
static int myVar = 0;
public SuperClass() {
myVar = giveValue();
}
public abstract int giveValue();
}
Subclass:
public class SubClass extends SuperClass {
#Override
public int giveValue() {
return 5; // individual value for the subclass
}
}
Rather than enforce that child class instances initialize the fields, you could follow a strategy of composition by having your parent class constructor take a parameter implementing an interface that provides the fields you wish to have initialized.
class Screen {
final Configuration config;
Screen(Configuration config) {
this.config = config;
}
// or
Screen(ConfigFactory configFactory) {
this.config = configFactory.make();
}
}
interface ConfigFactory {
Configuration make();
}
I would caution against requiring a subclass instance initializing the configuration, say using an abstract method implementation. The assignment in the parent class constructor occurs before the subclass instance is initialized, implicitly making proper computation of the configuration static.
If the computation isn't static, you risk null references or NullPointerExceptions by developers following you (or yourself if your memory is less than perfect). Make it easier on your collaborators (and yourself) and make the constraints explicit.
As mentioned by #Ketan in #B T's answer, invoking an overridable method from constructor is not especially a good practice (https://help.semmle.com/wiki/display/JAVA/Non-final+method+invocation+in+constructor)
One way to avoid this problem consists in having an abstract (protected) getter for the field. Hence the superclass doesn't have the field anymore, but it is still accessible in the super class using the getter. Each subclass is forced to declare the field because it must override the abstract getter.
Superclass:
public abstract class SuperClass {
public SuperClass() {}
protected abstract int getMyVar();
public void functionUsingMyVar(){
int a = 12 + getMyVar();
}
}
Subclass1:
public class SubClass1 extends SuperClass {
private int myVar;
public SubClass1() {
super();
myVar = 1;
}
#Override
protected int getMyVar(){
return myVar;
}
}
Subclass2:
public class SubClass2 extends SuperClass {
private int myVar;
public SubClass2() {
super();
myVar = 1;
}
#Override
protected int getMyVar(){
return myVar;
}
}
instead of having for the superclass (where giveValue() is overridable and called in the constructor) :
public abstract class SuperClass {
private int myVar;
public SuperClass() {
myVar = giveValue();
}
protected abstract int giveValue();
public void functionUsingMyVar(){
int a = 12 + myVar;
}
}

Is this an Instantiation of Abstract Class?

If Abstract class cannot be instantiated, then how can the variables
access and methods access of the abstract class A even without
extending is achieved in the class check (as you can see in the below
code)
Is the created a an object of abstract class A?
CODE
abstract class A
{
int a=10;
public A()
{
System.out.println("CONSTRUCTOR ONE");
}
public A(String value)
{
System.out.println("CONSTRUCTOR "+value);
}
void add(int sum)
{
System.out.println("THE SUM IS:"+sum);
}
int sub(int a,int b )
{
return(a-b);
}
}
public class check
{
public check()
{
new A("TWO"){};
}
public static void main(String args[])
{
int a,b,sum;
a=10;
b=15;
sum=a+b;
A s = new A() {};
new check();
s.add(sum);
int subb=s.sub(35,55);
System.out.println("THE SUB IS:"+subb);
System.out.println("THE VALUE OF A IS:"+s.a);
}
}
OUTPUT
CONSTRUCTOR ONE
CONSTRUCTOR TWO
THE SUM IS:25
THE SUB IS:-20
THE VALUE OF A IS:10
BUILD SUCCESSFUL (total time: 0 seconds)
The new A() {} call creates an anonymous subclass and instantiates that. Since A does not contain any abstract methods, this works.
You are creating subclass of A with this code -
A s = new A() {};
and here as well -
public check()
{
new A("TWO"){};
}
Whereas, the normal syntax for instantiation is this -
A a = new A();
which would give compilation error if you try to run this code. As such, you don't have any abstract method in your class, and hence a nominal subclass suffices and you get your code executed.
HTH,
- Manish
The normal use case is, you'd write new MyAbstractClass(){ and then implement whatever abstract methods you need to implement (and/or override existing non-abstract methods), and the compiler will infer a non-abstract subclass for you. Since your class doesn't have any abstract methods, it's not necessary to override anything.
A is marked abstract but has no abstract methods so when you do new A() {} you are providing an implementation that has nothing in it thus you are providing a concrete implementation and the class is complete.
Disregarding "visibility" (public, private, package scope, etc)... you generally need a class instance to access class members.
An exception is static classes.
Otherwise, if you have an abstract base class, you'll need to subclass to get an instance.
In your case, however, the class isn't really "abstract" (despite your attempting to label it as such). Simply because there are no abstract members or methods.
You created abstract class A without any abstract method.
Abstract classes cannot be instantiated, but they can be subclassed.
An abstract method is a method that is declared without an implementation.
In the constructor check() you just created anonymous class and call constructor A(String value).
new A("TWO"){};
This is a anonymous subclass .
1. This class create and instantiate at the same time...
2. No name of that class..
3. Because there is no name so it must need a parent .
You can get name by s.getClass().getName(); which return A$1....
A s = new A() {};
on the right side there is a new anonimus class which is inherited from A.A class haven't abstract methods so in your new anonimus class you don't need to override any methods.

Abstract class in Java

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

Categories