Java基础--抽象类与接口
2020-12-13 06:22
标签:def str ext auth int static nts super print Java基础--抽象类与接口 标签:def str ext auth int static nts super print 原文地址:https://www.cnblogs.com/mxh-java/p/11176300.html抽象类:
/**
* 抽象类,对类的抽象描述,包括属性、方法的抽象描述
* @author 尘世间迷茫的小书童
*
*/
public abstract class Myabstract {
/**
* 抽象类属性想要被子类继承,修饰符不能为private
*/
public String name;
public String sex;
public int age;
/**
* 抽象类中的方法可以有选择的实现
*/
public void testDo() {
}
public void testDo(String param) {
System.out.println("hello world " + param);
}
public Myabstract() {}
}
/**
* 子类通过extend继承抽象类
* @author 尘世间迷茫的小书童
*
*/
class People extends Myabstract{
/**
* 抽象类可以有构造方法,只是不能直接创建抽象类的实例对象而已。
* 在继承了抽象类的子类中通过super(参数列表)调用抽象类中的构造方法
*/
public People() {
super();
}
@Override
public void testDo() {
System.out.println("my name is " + this.name);
}
}
接口:
/**
* interface是对method的抽象描述,
* interface解决单继承问题
* interface可以解耦合
* @author 尘世间迷茫的小书童
*
*/
public interface MyInterface {
/**
* interface里的变量修饰符 public static final,变量不可修改
*/
public static final String name = "小米";
public static final String sex = "男";
public static final int age = 23;
/**
* method对行为方法的抽象,不需要方法体
* @return
*/
public String testDo();
/**
* jdk1.8以后interface可以有方法体,需要加default关键字
* @param param
*/
public default void testDo(String param) {
System.out.println("hello world " + param);
}
}
/**
* 实现类通过implements实现接口的所有方法
* @author 尘世间迷茫的小书童
*
*/
class Person implements MyInterface{
@Override
public String testDo() {
return "my name is " + this.name;
}
}