既然父类的属性设定为private,那为何还可以在它的子类中用super()访问
public class Work {
private String workname;//工作名称
public String getWorkname() {
return workname;
}
public void setWorkname(String workname) {
this.workname = workname;
}
public Work(){}//无参构造
public Work(String name){//有参构造
this.setWorkname(name);
}
//父类的方法
public void descraption(){//编写工作描述的方法
System.out.println("开心工作");
}
}
public class TestWork extends Work {
private int example;//测试用例个数
private int bug;//Bug个数
public int getExample() {
return example;
}
public void setExample(int example) {
this.example = example;
}
public int getBug() {
return bug;
}
public void setBug(int bug) {
this.bug = bug;
}
public TestWork(){}//无参构造
public TestWork(String workname,int example,int bug){
super(workname);
this.setExample(example);
this.setBug(bug);
}
//重写父类方法
public void descraption(){
System.out.println(this.getWorkname()+"的日报是,今天编写了"+this.getExample()+"个测试用例,发现了"+this.getBug()+"个Bug");
}
}122
收起
正在回答
2回答
这个是通过继承的方式访问的 ,如果你在子类中定义父类的对象去访问私有属性,就是不能访问的。祝学习愉快!
摄影祖师爷
2018-05-20 21:34:13
兄弟你是怎么做到的,我子类super后面加父类的私有属性,访问不到的。
package com.my.animal;
public class Animal {
private String name;
private int age;
public String kind;
public Animal() {
}
public Animal(String name, int age, String kind) {
super();
this.setName(name);
this.age = age;
this.kind = kind;
}
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;
}
}
package com.my.cat;
import com.my.animal.Animal;
public class Cat extends Animal{
private String weight;
public Cat() {
}
public Cat(String name,String weight) {
super(name);
this.weight = weight;
this.setName(name);
}
public void run() {
System.out.println(this.getName()+"is running happily and his age is"+this.getAge());
}
}
Java零基础入门18
- 参与学习 人
- 提交作业 7317 份
- 解答问题 14452 个
想要入门学编程?多年一直活跃在编程语言排行版前列的Java是一个很好的选择。本路径将从Java基础语法、面向对象、常用工具类三部分,为你开启软件开发的大门!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星