目录
一、super的作用
super 代表父类的引用, 用于访问父类的属性、 方法、 构造器
二、基本语法
第一条
访问父类的属性,但不能访问父类的private属性
例子:
父类
package com.hspedu.super_;
public class A {
public int n1 = 100;
protected int n2 = 200;
int n3 = 300;
private int n4 = 400;
//访问父类的属性,但不能访问父类的private属性
public void test100(){
}
protected void test200(){
}
void test300(){
}
private void test400(){
}
}
子类
package com.hspedu.super_;
public class B extends A{
//访问父类的属性,但不能访问父类的private属性
public void hi() {
System.out.println(super.n1 + " " + super.n2 + " " + super.n3 + " " + super.n4);
}
}
在IDEA中super.n4会变成红色报错
'n4' has private access in 'com.hspedu.super_.A'
原因:n4在父类A类中是private属性
第二条
访问父类的方法,但不能访问父类的private方法
同属性一样,private方法也会报错
'test400()' has private access in 'com.hspedu.super_.A'
第三条
访问父类的构造器,super(参数列表):只能放在构造器的第一句,只能出现第一句
在父类中创建三个构造器
package com.hspedu.super_;
public class A {
public int n1 = 100;
protected int n2 = 200;
int n3 = 300;
private int n4 = 400;
//默认无参构造器
public A() {
}
//一个参数的有参构造器
public A(String name) {
}
//两个参数的有参构造器
public A(String name, int age) {
}
//访问父类的属性,但不能访问父类的private属性
public void test100(){
}
protected void test200(){
}
void test300(){
}
private void test400(){
}
}
在子类的构造器中访问(只能在构造器中访问,普通方法不能访问),因为必须在第一句,所以只能用一次
报错原因
三个只能用一个