java是单继承:
一个类最多只能有一个直接的父类。但是有多个间接的父类。
class Ye{
String name;
}
class Fu extends Ye{
}
//
class Zi extends Fu{
}
class Demo6
{
public static void main(String[] args)
{
// System.out.println("Hello World!");
Zi zi =new Zi();
zi.name = "狗娃";
}
}
接口:
接口:拓展功能的。 usb接口.。。
接口的定义格式:
interface 接口名{
}
接口要注意的事项 :
1. 接口是一个特殊的类。
2. 接口的成员变量默认的修饰符为: public static final 。那么也就是说接口中的成员变量都是常量。
3. 接口中 的方法都是抽象的方法,默认的修饰符为: public abstract。
4. 接口不能创建对象。
5. 接口是没有构造方法的。
6. 接口是给类去实现使用的,非抽象类实现一个接口的时候,必须要把接口中所有方法全部实现。
实现接口的格式:
class 类名 implements 接口名{
}
接口的作用:
1. 程序的解耦。 (低耦合)
2. 定义约束规范。
3. 拓展功能。
interface A{
//成员变量
public static final int i=10;
//成员函数
public void print();
}
class Demo7 implements A{ // Demo7就实现了A接口
public static void main(String[] args)
{
Demo7 d = new Demo7();
d.print();
}
//实现接口中的方法
public void print(){
System.out.println("这个是接口中的print方法...");
}
}
接口的需求:
//普通的铅笔类
class Pencil{
String name;
public Pencil(String name){
this.name = name;
}
public void write(){
System.out.println(name+"沙沙的写...");
}
}
//橡皮接口
interface Eraser{
public void remove();
}
//带橡皮的铅笔
class PencilWithEraser extends Pencil implements Eraser {
public PencilWithEraser(String name){
super(name);
}
public void remove(){
System.out.println("涂改,涂改....");
}
}
class Demo8
{
public static void main(String[] args)
{
//System.out.println("Hello World!");
PencilWithEraser p = new PencilWithEraser("2B铅笔");
p.write();
p.remove();
}
}
/*
需求:在现实生活中有部分同学在学校期间只会学习,但是有部分学生除了学习外还会赚钱。
interface (定义接口)
implements (实现接口)
分析:
普通的学生类
接口
会挣钱的学生
*/
//普通的学生类
class Student{
String name;
public Student(String name){
this.name = name;
}
public void study(){
System.out.println(name+"好好学习");
}
}
//挣钱是学生拓展的功能---定义在接口上
interface Money{
public void makeMoney();
}
//会挣钱的学生
class MoneyStudent extends Student implements Money{
public MoneyStudent(String name){
super(name);
}
public void makeMoney(){
System.out.println(name+"好好挣钱,然后交学费!");
}
}
class Demo9
{
public static void main(String[] args)
{
Student s = new Student("李金华");
s.study();
//s.makeMoney();
MoneyStudent m = new MoneyStudent("孙双双");
m.study();
m.makeMoney();
}
}