`
zhangcxy
  • 浏览: 41466 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

抽象类和接口

    博客分类:
  • JAVA
阅读更多

1、接口是公开的,里面不能有私有的方法或变量,是用于让别人使用的,而抽象类是可以有私有方法或私有变量的

2、实现接口的一定要实现接口里定义的所有方法,而实现抽象类可以有选择地重写方法,抽象类中的抽象方法必须要在子类中实现,一般的应用里,最顶级的是接口,然后是抽象类实现接口,最后才到具体类实现。 3、接口可以实现多重继承,而一个类只能继承一个超类,但可以通过继承多个接口实现多重继承,接口还有标识(里面没有任何方法,如Remote接口)和数据共享(里面的变量全是常量)的作用。

 

一个抽象类

public abstract class Corp {
    
    protected abstract void produce(){};
    protected abstract void shell();
    protected void makeMoney(){
        this.produce();
        this.shell();
        System.out.println("kkkkkkkkkkkkkkk");
        
    }
    

}

 子类:

public class ShiChang extends Corp {

    @Override
    protected void produce() {
        System.out.println("iiiiiiiiiiiiproduce");
    }

    @Override
    protected void shell() {
        System.out.println("iiiiiiiiiiiishell");

    }
    
    public void makeMoneyllllllll(){
        super.makeMoney();
        System.out.println("oooooooooooooooooo");
    }
    

}

 接口:

public interface ILeaf {
//获得信息
public String getInfo();
}

 

 

实现类:

public class Leaf implements ILeaf {

private String name = "";
private String position = "";
private int salary=0;


//通过构造函数传递信息
public Leaf(String name,String position,int salary){
this.name = name;
this.position = position;
this.salary = salary;
}

public String getInfo() {
String info = "";
info = "名称:" + this.name;
info = info + "\t职位:"+ this.position;
info = info + "\t薪水:"+this.salary;
return info;
}
}

使用方法:

ILeaf a = new Leaf("a","开发人员",2000);

 再看一个例子:

public class WangPo implements KindWomen {
private KindWomen kindWomen;
public WangPo(){ //默认的话,是潘金莲的代理
this.kindWomen = new PanJinLian();
}
//她可以是KindWomen的任何一个女人的代理,只要你是这一类型
public WangPo(KindWomen kindWomen){
this.kindWomen = kindWomen;
}
public void happyWithMan() {
this.kindWomen.happyWithMan(); //自己老了,干不了,可以让年轻的代替
}
public void makeEyesWithMan() {
this.kindWomen.makeEyesWithMan(); //王婆这么大年龄了,谁看她抛媚眼?!
}
}

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics