There are two types of methods in JAVA
1.
Concrete methods
2.
Abstract methods
Q) What are the difference between
concrete method and abstract method?
Ans):-
1.
Concrete method is a java method, it must have
both method declaration and method implementation.
Abstract method is a java method, it will
have only method, it will have only method declaration without implementation.
2.
To declare concrete method no need to use any
special keyword.
To declare abstract method we must use
“abstract” keyword.
3.
Concrete method are able to pr4ovide class
sharability.
Abstract method are able to provide more
sharability.
4.
Concrete method are allowed in classes and
abstract classes.
Abstract method are allowed in abstract
classes and interface.
Ex:-
void add(int i,int j)
{
int
k=i+j;
System.out.println(k);
}
Note:-
Concrete method are allowed in class and abstract classes
Ex:-
abstract void add(int i,int j);
Note:-
Abstract method are allowed in abstract class and interface
class.
Date: july-16-2016
2. Abstract class
Abstract class is a java feature, it
able to zero or more number of concrete method and zero or more number of
abstract methods.
In java applications, we are able
to declare abstract class as without having abstract methods.
In java applications, to declare a
class And an abstract class then it is not all mandatory condition to have declare one abstract method, but to
declare a method as an abstract method then the respective class must be
abstract class.
In java application, for abstract
classes, we are able to declare reference variables, but, we are unable to
create objects.
Procedure to use abstract
classes in java applications
1.
Declare an abstract class with “abstract”
keyword.
2.
Declare concrete method and abstract method in
abstract class as per the application requirement.
3.
Declare a subclass for the abstract class.
4.
Provide implementation for the abstract method
In the sub class which are declare in the abstract class.
5.
In main class, in main() method, create object
for the sub class and declare reference variable either for abstract class or
for sub class.
6.
Access abstract class members.
Note:-
If we declare reference variable for abstract class then we
are able to access only abstract class members, we are unable to access
subclass members. If we declare reference variable for subclass. then we are able to access both abstract
class member and subclass members.
Ex code :-
abstract class A
{
void
m1()
{
System.out.println("m1-A");
}
abstract
void m2();
abstract
void m3();
}
class B extends A
{
void
m2()
{
System.out.println("m2-B");
}
void
m3()
{
System.out.println("m3-B");
}
void
m4()
{
System.out.println("m4-B");
}
}
class Test
{
public
static void main(String[] args)
{
//A
a=new A();---->Error
A
a=new B();
a.m1();
a.m2();
a.m3();
//a.m4();---->Error
B
b=new B();
b.m1();
b.m2();
b.m3();
b.m4();
}
}
Output:-
m1-A
m2-B
m3-B
m1-A
m2-B
m3-B
m4-B
Date july-17-2016
No comments:
Post a Comment