Java基础之继承

Father父类

public class Father {
	public String firstName;	
	private int age;
	
	public Father(String firstName, int age) {
		this.firstName = firstName;
		this.age = age;
	}

	private void privateMethod() {
		System.out.println("私有方法调用了!");
	}
	
	public int getAge() {
	    return age;
	}
	
	public void testMethod() {
	    this.privateMethod();
	}

}

Child子类

public class Child extends Father{
	public Child(String firstName, int age) {
		super(firstName, age);
	}

}

Test测试类

public class Test {
	public static void main(String[] args) {		
		Child c = new Child("费", 24);
		// 访问父类姓氏
		System.out.println(c.firstName);
		// 共有方法,访问私有属性
		System.out.println(c.getAge());
		// 共有方法,访问私有方法
		c.testMethod();
	}
}
结果:
费
24
私有方法调用了!

个人总结

1、Java不支持多继承。
2、子类可以继承父类的所用属性和方法,只是私有属性和私有方法不可见而已,可以通过共有方法去访问它们。

原文地址:https://www.cnblogs.com/feiqiangsheng/p/11109332.html