您的位置:首页 > 编程语言 > Java开发

java抽象类、抽象方法、接口、实现接口详解

2017-10-16 16:54 525 查看
对于java中的抽象类,抽象方法,接口,实现接口等具体的概念就不在这里详细的说明了,网上书本都有很多解释,主要是我懒,下面通过一个例子来说明其中的精髓要点,能不能练成绝世武功,踏上封王之路,就看自己的的啦(不要误会,我指的只是我自己啦啦)

用接口实现一个简单的计算器


1、利用接口做参数,写个计算器,能完成
+-*/运算


(1)定义一个接口Compute含有一个方法int computer(int n,int m);

(2)设计四个类分别实现此接口,完成
+-*/运算


(3)设计一个类UseCompute,含有方法: public void useCom(Compute com, int one, int two)

此方法要求能够:



1.用传递过来的对象调用computer方法完成运算

2.输出运算的结果

(4)设计一个测试类,调用UseCompute中的方法useCom来完成
+-*/运算


//父类.并且使用用接口
package cn.yjlblog.wwww;

public interface Compute {
int computer(int n,int m);//抽象方法,胜率abstract ,public

}

//子类add 实现加法运算
package cn.yjlblog.wwww;

public class add implements Compute{

@Override //接口的实现类和抽象类的子类是一样的,要想可以使用new 一个对象,就必须对“抽象类”里的方法
//进行重写
public int computer(int n, int m) {
// TODO Auto-generated method stub
return n+m;
}

}

package cn.yjlblog.wwww;
//子类subtract 实现减法运算
public class subtract implements Compute{

@Override
public int computer(int n, int m) {
// TODO Auto-generated method stub
return n-m;
}

}

子类multiplied 实现乘法运算
package cn.yjlblog.wwww;

public class multiplied implements Compute{

@Override
public int computer(int n, int m) {
// TODO Auto-generated method stub
return n*m;
}

}

package cn.yjlblog.wwww;
//子类divided 实现整除运算
public class divided implements Compute{

@Override
public int computer(int n, int m) {
// TODO Auto-generated method stub
return n/m;
}

}

//应用类UseComepute 用来
package cn.yjlblog.wwww;

public class UseComepute {
public void useCom(Compute com,int one,int two){
int x = com.computer(one, two);
System.out.println("运算结果为:"+x);

}

}

//测试类Test
package cn.yjlblog.wwww;

public class Test {
public static void main(String[] args) {
UseComepute uc = new UseComepute();//应用类生成对象,使用useCome 方法
int one = 10;
int two = 20;
Compute ad = new add();//接口的多态
Compute sub = new subtract();
Compute mul= new multiplied();
Compute div = new divided();
uc.useCom(ad, one, two);
uc.useCom(sub, one, two);
uc.useCom(mul, one, two);
uc.useCom(div, one, two);

//哈哈,类的名字忘记大写了

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: