Thursday 19 March 2020

What is Abstract class and abstract Method in Java -tccicomputercoaching.com

Abstract means something, which is in thoughts but not it exists in reality. It is like that we know that what should be done, but we don’t know how it would be done.

Take an example, there is a ‘Shape’ class which contains a method ‘area()’ but we cannot implement area() method here as we do not know what will be the shape(a square, a rectangle, a triangle or any other shape) in future. In that case, we will declare area() in the Shape class and will implement the same method in our subclasses as per the requirement.



Example:

1. public abstract class Shape
2. {
3. public abstract void area(int var); // Abstract method
4. }
5.
6. public class Circle extends Shape
7. {
8. int radius;
9. double pi=3.14;
10. public void area(int var)
11. {
12. radius=var;
13. System.out.println("Arear of Circle: "+(pi*radius*radius));
14. }
15. }
16. public class Square extends Shape
17. {
18. int side;
19. public void area(int var)
20. {
21. side=var;
22. System.out.println("Area of Square: "+side*side);
23. }
24. }
25. public class Result
26. {
27. public static void main(String[] args)
28. {
29. Shape obj=new Square();
30. obj.area(4);
31.
32. Shape obj1=new Circle();
33. obj1.area(3);
34. }
35. }

In JAVA, Abstraction can be achieved using the abstract class, abstract methods, and interface. Using the abstract class we can achieve the different level of abstraction, but using the interfaces we can achieve 100% abstraction.

Abstract Class:

1. An abstract class would be declared using ‘abstract’ keyword.
2. Creation of object is not possible of an abstract class.
3. It may contain data members, methods, abstract methods, constructors.
4. Data members can’t be abstract.
5. It must be inherited by the subclass(es) using ‘extends’ keyword.
6. The subclass should implement each and every abstract method declared in Super Class. Otherwise, subclass would act like abstract class which needs to be extended further.

Abstract Method:

1. An abstract method can be placed within an abstract Class only.
2. It would be declared using ‘abstract’
3. The abstract method should be declared only without any implementation
4. It can be implemented only in the subclass(concrete class) using ‘extends’ or ‘implements’.

TCCI teach Programming Language like C, C++, Java, Python, Database Management, Python, Data Structure HTML, CSS, Java Script, .Net, PHP, System Programming Compiler Design, Boot Strap, Angular Js etc.

Call us @ 9825618292

Visit us @ http://tccicomputercoaching.com/

No comments:

Post a Comment