当子类重写父类的方法后,子类对象将无法访问父类被重写的方法,为了解决这个问题,Java提供了super关键字,super关键字可以在***“子类中”***调用父类的**普通属性、方法以及构造方法**。
super不能出现在静态方法中
package sk; //父类
public class Animal {
private String name;
private int age;
int num=10;
public Animal() {}
public Animal(String name,int age)
{this.name=name;this.age=age;}
public String getName()
{return name;}
public void setName(String name)
{this.name = name;}
public int getAge()
{return age;}
public void setAge(int age)
{this.age = age;}
public void eat()
{System.out.print("模拟吃饭");}
}
package sk; // 子类猫
public class cat extends Animal {
public cat()
{ }
public cat(String name,int age)
{ super(name,age); }//在子类中调用父类的构造方法
public void eat()
{
super.eat();//在子类继承父类并重载父类函数下,保留父类原有函数并在子类中使用
//"模拟吃饭"
System.out.println(super.num);//调用父类"非私有"属性,"本以为可以用C.num来着,但发现没,“本类中”还没创建新对象,所以本类中不能用c来调"
System.out.println("猫吃鱼");
}
}
package sk; //子类狗
public class dog extends Animal {
private String color;
public String getColor()
{
return color;
}
public void setColor(String color)
{
this.color = color;
}
public dog(String name ,int age,String color)
{
super(name,age);//将属于父类的参数传过去
this.color=color;//dog为自己的属性赋值
}
public void eat()
{
System.out.println("狗吃屎");
super.eat();//"模拟吃饭"
}
}
package sk;
public class test {
public static void main(String[] args){
cat c=new cat();
System.out.println(c.num);
//这句是不能运行的System.out.println(super.num);// super不能出现在静态方法中。静态方法中,就是方法前面加上static关键字的方法
c.eat();
dog d=new dog("傻狗",2,"black");
System.out.println(d.getName()+d.getAge()+"岁了是"+d.getColor()+"颜色的");
d.eat();
}
}
06-05
6182
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
01-22
3万+
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-27
4666
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)