温馨提示×

java自动创建子类对象怎么实现

小亿
107
2023-09-22 10:30:29
栏目: 编程语言

在Java中,可以通过继承和实现接口来自动创建子类对象。

  1. 继承:子类通过继承父类,可以自动获得父类的属性和方法。使用关键字extends指定父类,子类可以通过super关键字调用父类的构造方法和方法。
class Parent {
public void method1() {
System.out.println("Parent method1");
}
}
class Child extends Parent {
public void method2() {
System.out.println("Child method2");
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
child.method1();  // 调用父类的方法
child.method2();  // 调用子类的方法
}
}
  1. 接口:类可以实现一个或多个接口,接口中定义了一组抽象方法,类需要实现这些方法。使用关键字implements指定接口,类需要实现接口中的所有抽象方法。
interface MyInterface {
void method1();
}
class MyClass implements MyInterface {
public void method1() {
System.out.println("MyClass method1");
}
}
public class Main {
public static void main(String[] args) {
MyClass myClass = new MyClass();
myClass.method1();  // 调用实现类的方法
}
}

通过继承和实现接口,可以方便地创建子类对象并使用其方法。

0