接触过java,但是忘记了,刚扫完了一遍c++,忘记了这两个语法区别。
Java 继承
继承可以使用 extends
和 implements
这两个关键字来实现继承,
public class Animal {
private String name;
private int id;
public Animal(String myName, int myid) {
name = myName;
id = myid;
}
public void eat(){
System.out.println(name+"正在吃");
}
public void sleep(){
System.out.println(name+"正在睡");
}
public void introduction() {
System.out.println("大家好!我是" + id + "号" + name + ".");
}
}
public class Penguin extends Animal {
public Penguin(String myName, int myid) {
super(myName, myid);
}
}
public class Mouse extends Animal {
public Mouse(String myName, int myid) {
super(myName, myid);
}
}
java不支持多继承, 使用 implements
关键字可以变相的使java具有多继承的特性,使用范围为类继承接口的情况,可以同时继承多个接口(接口跟接口之间采用逗号分隔)。
public interface A {
public void eat();
public void sleep();
}
public interface B {
public void show();
}
public class C implements A,B {
}
super/this
class Animal {
Animal(){
System.out.println("Animal()");
}
Animal(int n) {
System.out.println("Animal(int n)");
this.n = n;
}
void eat() {
System.out.println("animal : eat");
}
}
class Dog extends Animal {
void eat() {
System.out.println("dog : eat");
}
void eatTest() {
this.eat(); // this 调用自己的方法
super.eat(); // super 调用父类方法
}
}
public class Test {
public static void main(String[] args) {
Animal a = new Animal();
a.eat();
Dog d = new Dog();
d.eatTest();
}
}
final关键字
inal 关键字声明类可以把类定义为不能继承的,即最终类;或者用于修饰方法,该方法不能被子类重写: