The uses of abstract class constructor and some advantage of Abstract class constructor as well as Example of abstract class constructor.


You would define a constructor in an abstract class in one of these situations:


1) You have defined final fields or instance variables in the abstract class but you did not initialize them in this case, you MUST have a constructor to initialize these final fields or instance variables.

2) You want to perform some initialization (to fields of the abstract class) before the instantiation of a subclass actually takes place.

3) For constructor Chaining

Note:

You may define more than one constructor (with different arguments) or You Can Overload as many Constructor as you want in an Abstract Class.
 Advantage of Abstract class constructor
Abstract class constructor


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).




abstract class Product {
		String prodName;

		public Product(String prodName) {
			this.prodName = prodName;
		}

		abstract public String getProductPrice(int price);
	}

In the above example, we have made an abstract class name Product and have a variable prodName and method is getProductPrice.
In this product class, we make a common method getProductprice which is used when we inherit or extends the Product class to any product company.
class Lotus extends Product {

		public Lotus(String prodName) {
			super(prodName);

		}

		@Override
		public String getProductPrice(int price) {
			return prodName + " : " + price;
		}

	}

	class Philips extends Product {

		public Philips(String prodName) {
			super(prodName);

		}

		@Override
		public String getProductPrice(int price) {
			return prodName + " : " + price;
		}

	}

As you can see Lotus and Philips class both extend or inherit Product for providing some implementation.  

	class ProductNameAndPrice {

		public static void main(String[] args) {
			Lotus l = new Lotus("Lotus");
			System.err.println(l.getProductPrice(25));

			Philips p = new Philips("Philips");
			System.err.println(p.getProductPrice(3000));

		}
	}

As you know that 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.
So using super you can pass values in a constructor of the abstract class.

Post a Comment

Previous Post Next Post