抽象类(0到100%)
接口(100%)
必须使用abstract关键字声明抽象类。
它可以具有抽象和非抽象方法。
无法实例化。
它可以具有构造函数和静态方法。
它可以具有最终方法,这些方法将强制子类不更改方法的主体。
abstract class A{
}
abstract void printStatus();
//no method body and abstract
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){
System.out.println("running safely");
}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
running safely
abstract class Shape{
abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end userclass Rectangle extends Shape{
void draw(){
System.out.println("drawing rectangle");
}
}
class Circle1 extends Shape{
void draw(){
System.out.println("drawing circle");
}
}
//In real scenario, method is called by programmer or userclass TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();
//In a real scenario, object is provided through method, e.g., getShape() methods.draw();
}
}
drawing circle
abstract class Bank{
abstract int getRateOfInterest();
}
class SBI extends Bank{
int getRateOfInterest(){
return 7;
}
}
class PNB extends Bank{
int getRateOfInterest(){
return 8;
}
}
class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}
}
Rate of Interest is: 7 %Rate of Interest is: 8 %
//Example of an abstract class that has abstract and non-abstract methods abstract class Bike{
Bike(){
System.out.println("bike is created");
}
abstract void run();
void changeGear(){
System.out.println("gear changed");
}
}
//Creating a Child class which inherits abstract class class Honda extends Bike{
void run(){
System.out.println("running safely..");
}
}
//Creating a Test class which calls abstract and non-abstract methods class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}
bike is created running safely.. gear changed
class Bike12{
abstract void run();
}
compile time error
interface A{
void a();
void b();
void c();
void d();
}
abstract class B implements A{
public void c(){
System.out.println("I am c");
}
}
class M extends B{
public void a(){
System.out.println("I am a");
}
public void b(){
System.out.println("I am b");
}
public void d(){
System.out.println("I am d");
}
}
class Test5{
public static void main(String args[]){
A a=new M();
a.a();
a.b();
a.c();
a.d();
}
}
Output:I am a I am b I am c I am d