Abstract classes and constructors java

Abstract Class in Java with example

A class that is declared using “abstract” keyword is known as abstract class. It can have abstract methods(methods without body) as well as concrete methods (regular methods with body). A normal class(non-abstract class) cannot have abstract methods. In this guide we will learn what is a abstract class, why we use it and what are the rules that we must remember while working with it in Java.

An abstract class can not be instantiated, which means you are not allowed to create an object of it. Why? We will discuss that later in this guide.

Why we need an abstract class?

Lets say we have a class Animal that has a method sound() and the subclasses(see inheritance) of it like Dog , Lion , Horse , Cat etc. Since the animal sound differs from one animal to another, there is no point to implement this method in parent class. This is because every child class must override this method to give its own implementation details, like Lion class will say “Roar” in this method and Dog class will say “Woof”.

Читайте также:  What is php and how to install it

So when we know that all the animal child classes will and should override this method, then there is no point to implement this method in parent class. Thus, making this method abstract would be the good choice as by making this method abstract we force all the sub classes to implement this method( otherwise you will get compilation error), also we need not to give any implementation to this method in parent class.

Since the Animal class has an abstract method, you must need to declare this class abstract.

Now each animal must have a sound, by making this method abstract we made it compulsory to the child class to give implementation details to this method. This way we ensures that every animal has a sound.

Abstract class Example

//abstract parent class abstract class Animal < //abstract method public abstract void sound(); >//Dog class extends Animal class public class Dog extends Animal < public void sound()< System.out.println("Woof"); >public static void main(String args[]) < Animal obj = new Dog(); obj.sound(); >>

Hence for such kind of scenarios we generally declare the class as abstract and later concrete classes extend these classes and override the methods accordingly and can have their own methods as well.

Abstract class declaration

An abstract class outlines the methods but not necessarily implements all the methods.

//Declaration using abstract keyword abstract class A < //This is abstract method abstract void myMethod(); //This is concrete method with body void anotherMethod()< //Does something >>

Rules

Note 1: As we seen in the above example, there are cases when it is difficult or often unnecessary to implement all the methods in parent class. In these cases, we can declare the parent class as abstract, which makes it a special class which is not complete on its own.

A class derived from the abstract class must implement all those methods that are declared as abstract in the parent class.

Note 2: Abstract class cannot be instantiated which means you cannot create the object of it. To use this class, you need to create another class that extends this this class and provides the implementation of abstract methods, then you can use the object of that child class to call non-abstract methods of parent class as well as implemented methods(those that were abstract in parent but implemented in child class).

Note 3: If a child does not implement all the abstract methods of abstract parent class, then the child class must need to be declared abstract as well.

Do you know? Since abstract class allows concrete methods as well, it does not provide 100% abstraction. You can say that it provides partial abstraction. Abstraction is a process where you show only “relevant” data and “hide” unnecessary details of an object from the user.

Interfaces on the other hand are used for 100% abstraction (See more about abstraction here).
You may also want to read this: Difference between abstract class and Interface in Java

Why can’t we create the object of an abstract class?

Because these classes are incomplete, they have abstract methods that have no body so if java allows you to create object of this class then if someone calls the abstract method using that object then What would happen?There would be no actual implementation of the method to invoke.
Also because an object is concrete. An abstract class is like a template, so you have to extend it and build on it before you can use it.

Example to demonstrate that object creation of abstract class is not allowed

As discussed above, we cannot instantiate an abstract class. This program throws a compilation error.

abstract class AbstractDemo < public void myMethod()< System.out.println("Hello"); >abstract public void anotherMethod(); > public class Demo extends AbstractDemo < public void anotherMethod() < System.out.print("Abstract method"); >public static void main(String args[]) < //error: You can't create object of it AbstractDemo obj = new AbstractDemo(); obj.anotherMethod(); >>
Unresolved compilation problem: Cannot instantiate the type AbstractDemo

Note: The class that extends the abstract class, have to implement all the abstract methods of it, else you have to declare that class abstract as well.

Abstract class vs Concrete class

A class which is not abstract is referred as Concrete class. In the above example that we have seen in the beginning of this guide, Animal is a abstract class and Cat , Dog & Lion are concrete classes.

  1. An abstract class has no use until unless it is extended by some other class.
  2. If you declare an abstract method in a class then you must declare the class abstract as well. you can’t have abstract method in a concrete class. It’s vice versa is not always true: If a class is not having any abstract method then also it can be marked as abstract.
  3. It can have non-abstract method (concrete) as well.

I have covered the rules and examples of abstract methods in a separate tutorial, You can find the guide here: Abstract method in Java
For now lets just see some basics and example of abstract method.
1) Abstract method has no body.
2) Always end the declaration with a semicolon(;).
3) It must be overridden. An abstract class must be extended and in a same way abstract method must be overridden.
4) A class has to be declared abstract to have abstract methods.

Note: The class which is extending abstract class must override all the abstract methods.

Example of Abstract class and method

abstract class MyClass < public void disp()< System.out.println("Concrete method of parent class"); >abstract public void disp2(); > class Demo extends MyClass < /* Must Override this method while extending * MyClas */ public void disp2() < System.out.println("overriding abstract method"); >public static void main(String args[]) < Demo obj = new Demo(); obj.disp2(); >>
overriding abstract method

Источник

Constructor in Java Abstract Class

Constructor is always called by its class name in a class itself. A constructor is used to initialize an object not to build the object. As we all know abstract classes also do have a constructor. So if we do not define any constructor inside the abstract class then JVM (Java Virtual Machine) will give a default constructor to the abstract class. If we want to know how to define user define constructors like constructors with argument or any kind of constructor inside the abstract class then you should follow the given procedure.

Note: An abstract class is a class declared with an abstract keyword.

Properties of an abstract class:

  • An abstract class can have an abstract and a non-abstract method.
  • It must be declared with an abstract keyword.
  • It can have a constructor, static method.
  • It can have a final method that prevents child class of abstract class not to change the body of the method
  • The abstract method contains no-body or in simple words, you can say that you can’t define an abstract method inside an abstract class. We can define an abstract method inside the derived class of its abstract class.
  • The object of the abstract class can’t be instantiated it means you can’t create an abstract class object directly but you can create its object by reference to its child class.
  • If you define your own constructor without arguments inside an abstract class but forget to call your own constructor inside its derived class constructor then JVM will call the constructor by default.
  • So if you define your single or multi-argument constructor inside the abstract class then make sure to call the constructor inside the derived class constructor with the super keyword.

Implementation: Here in this program, we are going to multiply two numbers by using the following above approach as mentioned.

Step 1: We create an abstract class named ‘Content’ and define a user define a constructor with one argument, variable with name ‘a’, and an abstract method named as ‘multiply’

Step 2: We create a class that must be derived from this abstract class ‘Content’ named ‘GFG’. Inside GFG class we are going to define a constructor and inside the method call the parent class constructor by using the super keyword and define the abstract method of its parent class in it.

Step 3: Now in the main class of our function that is ‘GeeksforGeeks’ here, where we will create an object of abstract class ‘Content’ by reference to its derived class object. Then we call the method of the abstract class by its object.

Step 4: Inside the method, we multiply both the value stored in the different variable names where one of the variables is the variable of an abstract class. We can access the variable of the abstract class by its derived class object.

Источник

Can Abstract class have Constructor in Java? Interview Question

Yes, an abstract class can have a constructor in Java. You can either explicitly provide a constructor to the abstract class or if you don’t, the compiler will add a default constructor of no argument in the abstract class. This is true for all classes and it also applies to an abstract class. For those who want to recall what is an abstract class in Java, it’s a class that can not be instantiated with the new() operator or any other way. In order to use an abstract class in Java, You need to extend it and provide a concrete class. An abstract class is commonly used to define a base class for a type hierarchy with default implementation, which is applicable to all child classes.

By the way, the difference between interface and abstract class in Java is also one of the popular and tricky Java questions and should be prepared well for Java interviews.

Can we declare constructor on abstract class in Java is a follow-up of other similar Java interview questions e.g. Can we override static method in Java?. Why does the interviewer ask these questions? Mainly because, trying to confuse programmer with the fact that since an abstract class can not be instantiated, why abstract class needs a constructor. In this Java Interview question article we will see that Abstract class can have a constructor in Java.

Why can an abstract class have a constructor in Java?

Now if we say we can not create an instance of an abstract class then why does Java adds a constructor in the abstract class. One of the reasons which make sense is when any class extends an abstract class, the constructor of sub-class will invoke the constructor of the super-class either implicitly or explicitly. This chaining of constructors is one of the reasons abstract classes can have constructors in Java.

Here is an example Java program, which proves that abstract class can have constructors in Java :

/** * Simple Java program to prove that abstract class can have constructor in Java. * @author http://java67.blogspot.com */ public class AbstractConstructorTest < public static void main(String args[]) < Server server = new Tomcat("Apache Tomcat"); server.start(); > > abstract class Server< protected final String name; public Server(String name)< this.name = name; > public abstract boolean start(); > class Tomcat extends Server< public Tomcat(String name) < super(name); >@Override public boolean start() < System.out.println( this.name + " started successfully"); return true; > > Output: Apache Tomcat started successfully

In this example Java program, we have an abstract class Server, which has a constructor with one parameter, which accepts the name. Subclass provides that name to superclass while creating a concrete instance of Server and overriding abstract method starts() . Since this program compiles and runs fine you can definitely say abstract class can have constructors in Java.

Can we declare constructor in abstract class in Java

Thanks for reading this article so far. If you like an object-oriented programming tutorial then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. — If you are serious about learning object-oriented programming and looking for a free online course to start with then you can also check this FREE Object Oriented Programming (OOPs) for JAVA Interviews course on Udemy. It’s completely free and you just need a free Udemy account to join this course.

Источник

Оцените статью