Java 继承性(继承的实现)

范例1:

class Person {
	private String name;
	private int age;

	public void setName(String name) {
		this.name = name;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getName() {
		return this.name;
	}

	public int getAge() {
		return this.age;
	}
}

class Student extends Person {
}

public class Demo04 {
	public static void main(String[] args) {
		Student stu = new Student();
		stu.setName("张三");
		stu.setAge(23);
		System.out.println("学生姓名:" + stu.getName() + ",年龄:" + stu.getAge() + "岁。");
	}
}

==============分割线==============

范例2:子类实例化对象之前会自动先实例化父类对象,调用了父类无参构造方法

class A{
	public A() {
		System.out.println("A、A类的构造方法");
	}
}

class B extends A{
	public B() {
		System.out.println("B、B类的构造方法");
	}
}

public class Demo04 {
	public static void main(String[] args) {
		new B();
	}
}

==============分割线==============

范例3:如果父类没有无参构造,就必须使用super()明确调用父类有参构造方法

class A{
	public A(String title) {
		System.out.println("A、A类的构造方法");
	}
}

class B extends A{
	public B(String title) {
		super(title);
		System.out.println("B、B类的构造方法");
	}
}

public class Demo04 {
	public static void main(String[] args) {
		new B("Hello");		
	}
}

你可能感兴趣的:(Java,继承性)