+ 2
What is the use of defining method as abstract in java?
5 ответов
+ 6
by making an abstract method Java knows an object which inherits from that class must have that method, so you can just call it, instead of checking if the object has the method.
example for better understanding:
classes:
-Person
-Teacher (inherits from Person)
-Student (inherits from Person)
in code:
Person[] people = new Person[2];
people[0] = new Teacher();
people[1] = new Student();
for(int i=0;i<people.length;i++){
people[i].saySomethingSmart();
}
explenation:
since the teacher and student inherit from Person they can both be put into an array of Person. In the Person the abstract method saySomethingSmart() does nothing, but it helps when we try to call the method for teachers and students since java can't be sure if they have the method or not, by inheriting java can be sure and there will be no runtime errors this way.
if you don't understand, it's not that important if your just starting...
+ 4
So that you can implement them in a subclass. Imagine you has a method/function that takes a parent class object as an argument through inheritance our subclasses would have the same methods as our superclass, but in our superclass we dont know exactly what some of the functions should do to meet all subclass needs, so we define an abstract method in the superclass, then we provide specific implementation details of that method in the subclass, then whatever method takes our parent class as an argument can call the abstract parent method, and any subclass passed as the argument would call the subclasses method, this is more commonly known as method over riding.
+ 4
Sometimes two or more different types (classes) of objects share common functionality derived from a parent for which there are no concrete instances.
+ 1
Abstract method indicates that it will have no body and the code can only be run when implemented in a sub class.
+ 1
Declaring a class as abstract means the class can not be instantiated using the new keyword with a constructor and must instead be instantiated by an anonymous class, and allows for the creation of abstract methods which contain no body.
Making classes abstract allows for abstraction to take place since abstract classes have abstract methods that MUST be implemented by a child class at some point, therefore an instance of this class can be given when you have a child class that extends this class that has unsafe methods you do not want to expose. Or, can act as a building block for other child classes that will end up inheriting these methods.
Furthermore, abstract classes are often used to accomplish the Liskov-Substitution principal, where the lowest possible superclass is declared, and thus based on inheritance and the above reasons could prove to be this class.