接口和抽象类

来源:互联网 发布:淘书网软件下载 编辑:程序博客网 时间:2024/05/21 06:18
1.抽象类中是否可以有private属性?是否可以有private方法?
答:可以有private属性和private方法(以下为验证代码)。因为抽象类可以有自己方法实现,自己方法的实现可能会用到自己的私有变量。抽象类自有方法可以调用私有方法,但实际中没有什么意义。
抽象类:
package test;

public abstract class TestAbstract {

     //抽象类中定义私有属性
     private String info = "1";

     //抽象类中定义私有方法,并调用私有属性
     private String getInfo(){
           return "【若这段话被输出,说明抽象类中可以定义私有方法】" + info;
     }

     //公共方法中调用私有方法
     public void test(){
           System.out.println("本方法中调用私有方法:" + getInfo());
     }

}
子类:
package test;

public class TestAbstractImpl extends TestAbstract{

}
测试类:
package test;
public class Test {

     public static void main(String[] args) {
           TestAbstractImpl testAbstractImpl = new TestAbstractImpl();
           testAbstractImpl.test();
     }
}
验证结果:
本方法中调用私有方法:【若这段话被输出,说明抽象类中可以定义私有方法】1

2.接口中是否可以有private属性?是否可以有private方法?
答:接口中只能有全局常量公共的抽象方法,不能有private属性和方法。

3.接口是否可以实现接口,是否可以实现抽象类?
答:接口可以继承接口(extends),但不能实现接口。接口不能继承和实现抽象类。

4.抽象类是否可以实现接口?
答:抽象类可以实现接口。


0 0
原创粉丝点击