子类不能继承父类的构造器(构造方法或者构造函数),但是父类的构造器带有参数的,则必须在子类的构造器中显式地通过super关键字调用父类的构造器并配以适当的当属列表。

如果父类有无参构造器,则在子类的构造器中用super调用父类构造器不是必须的,如果没有使用super关键字,系统会自动调用父类的无参构造器。

public class InheritanceDemo {
	public static void main(String args[]) {
		// SubClass sc = new SubClass();
		SubClass sc2 = new SubClass(200);
		sc2.eat();
	}

	public static class SuperClass {
		private int n;

		SuperClass() {
			System.out.println("SuperClass()");
		}

		SuperClass(int n) {
			System.out.println("SuperClass(int n):"+n);
			this.n = n;
		}
		void eat(){
			
		}
	}

	public static class SubClass extends SuperClass {
		private int n;

		SubClass() {
			//super(300);
			System.out.println("SuperClass");
		}

		public SubClass(int n) {
			//super(300);
			System.out.println("SubClass(int n):" + n);
			this.n = n;
		}
	}
}

  

相关文章:

  • 2022-12-23
  • 2022-02-27
  • 2022-12-23
  • 2021-07-28
  • 2021-07-11
  • 2021-05-12
  • 2021-07-06
  • 2021-12-24
猜你喜欢
  • 2021-08-25
  • 2021-07-23
  • 2021-05-15
  • 2021-10-12
  • 2021-09-30
  • 2021-05-21
相关资源
相似解决方案