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、子类可以继承父类的所用属性和方法,只是私有属性和私有方法不可见而已,可以通过共有方法去访问它们。

相关文章:

  • 2022-01-28
  • 2021-06-05
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-10
  • 2021-11-10
  • 2021-12-05
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-15
  • 2021-05-23
相关资源
相似解决方案