类的继承
先说一下类的继承,也就是extends关键字。想象一个例子,有一个电脑,电脑有很多的功能,包括,听歌,聊天,看视频,这时候可以根据电脑这个模型,来做出来一个平板电脑,平板电脑也能够听歌,看视频,但同时平板电脑也多了一些自己独有的功能。看一下代码实例:
父类代码:
package Test;
public class Computer {
String screen="液晶显示器";
void aaa() {
System.out.println("dsadasd");
}
}
子类代码:
package Test;
public class Pad extends Computer{
public static void main(String[] args) {
Pad pad =new Pad();
System.out.println("输出父类变量的值:"+pad.screen);
pad.aaa();
}
}
上面的代码,在主函数中创建子类的对象就可以直接调用父类的属性和方法。
方法重写
方法重写的概念很简单,其实就是对父类的方法在子类中重写。看下如下代码
父类代码:
public class Computer {
String screen="液晶显示器";
void aaa() {
System.out.println("dsadasd");
}
void showInput() {
System.out.println("双击点击打开图片");
}
}
子类代码:
public class Pad extends Computer{
void showInput() {
System.out.println("手指触摸点击图片");
}
public static void main(String[] args) {
Pad pad =new Pad();
Computer comp=new Computer();
// System.out.println("输出父类变量的值:"+pad.screen);
// pad.aaa();
comp.showInput();
pad.showInput();
}
}
运行结果:
双击点击打开图片
手指触摸点击图片
super关键字
super关键字可以直接调用父类的方法,属性等,这也是跟this关键字的使用区别。
一般super关键字在代码中使用可分为3种,调用父类的构造方法,调用父类的属性,和父类的成员方法。
代码格式如下:
super.属性
super();
super.方法名();
如果想要当前子类中的属性值等于父类的属性可以使用 this.属性=spuer.属性