// 父类
class Animal {
String name;
public Animal(String name) {
this.name = name;
}
public void eat() {
System.out.println(name + " is eating.");
}
}
// 子类继承自Animal类
class Dog extends Animal {
public Dog(String name) {
super(name);
}
public void bark() {
System.out.println(name + " is barking.");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog("Buddy");
myDog.eat(); // 继承自父类Animal
myDog.bark(); // 子类自己的方法
}
}
class Animal {
public void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Animal();
animal.makeSound(); // Output: Animal makes a sound
Dog dog = new Dog();
dog.makeSound(); // Output: Dog barks
}
}
public class SubClass extends SuperClass {
public SubClass() {
super(); // 调用父类的无参构造方法
}
}
访问父类的实例变量
使用super关键字可以访问父类中被子类覆盖的实例变量。
public class SuperClass {
int num = 10;
}
public class SubClass extends SuperClass {
int num = 20;
public void display() {
System.out.println("Subclass num: " + num); // 访问子类的num
System.out.println("Superclass num: " + super.num); // 访问父类的num
}
}
class Animal {
public void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
public void bark() {
System.out.println("Dog is barking");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Dog(); // 向上转型
animal.eat();
if (animal instanceof Dog) {//判断animal对象是否是Dog类的实例
Dog dog = (Dog) animal; // 向下转型
dog.bark();
}
}
}