您当前的位置: 首页 > 学无止境 > 心得笔记 网站首页心得笔记
【第6章:面向对象(高级)】_继承的基本实现
发布时间:2020-12-15 15:48:30编辑:雪饮阅读()
继承
继承可以继承到父类的一些属性和方法并在此基础上进行自己可选新增属性与方法。
class Pesron{
private String name ;
private int age ;
public void setName(String name){
this.name = name;
}
public void setAge(int age){
this.age = age ;
}
public String getName(){
return this.name ;
}
public int getAge(){
return this.age ;
}
}
class Student extends Pesron{
private String school;
public void setSchool(String school){
this.school=school;
}
public String getSchool(){
return this.school;
}
}
public class Hello{
public static void main(String args[]){
Student stu = new Student();
stu.setName("张三");
stu.setAge(30) ;
stu.setSchool("清华大学") ;
System.out.println("姓名:" + stu.getName() + ",年龄:" + stu.getAge() + ",学校:" + stu.getSchool());
}
}
D:\>javac Hello.java
D:\>java Hello
姓名:张三,年龄:30,学校:清华大学
java不支持多继承
class A{}
class B{}
class C extends A,B{}
public class Hello{
public static void main(String args[]){}
}
D:\>javac Hello.java
Hello.java:3: 需要 '{'
class C extends A,B{}
^
1 错误
但支持多层继承
class A{}
class B extends A{}
class C extends B{}
public class Hello{
public static void main(String args[]){}
}
D:\>javac Hello.java
D:\>java Hello
不可直接获取父类属性
class Pesron{
private String name ;
private int age ;
public void setName(String name){
this.name = name;
}
public void setAge(int age){
this.age = age ;
}
public String getName(){
return this.name ;
}
public int getAge(){
return this.age ;
}
}
class Student extends Pesron{
private String school;
public void setSchool(String school){
this.school=school;
}
public String getSchool(){
return this.school;
}
public void getPersonAttribute(){
System.out.println(name);
}
}
public class Hello{
public static void main(String args[]){
Student stu = new Student();
stu.setName("张三");
stu.setAge(30) ;
stu.setSchool("清华大学") ;
stu.getPersonAttribute();
}
}
D:\>javac Hello.java
D:\>javac Hello.java
Hello.java:26: name 可以在 Pesron 中访问 private
System.out.println(name);
^
1 错误
但可间接访问。。。
class Pesron{
private String name ;
private int age ;
public void setName(String name){
this.name = name;
}
public void setAge(int age){
this.age = age ;
}
public String getName(){
return this.name ;
}
public int getAge(){
return this.age ;
}
}
class Student extends Pesron{
private String school;
public void setSchool(String school){
this.school=school;
}
public String getSchool(){
return this.school;
}
public void getPersonAttribute(){
System.out.println(getName());
}
}
public class Hello{
public static void main(String args[]){
Student stu = new Student();
stu.setName("张三");
stu.setAge(30) ;
stu.setSchool("清华大学") ;
stu.getPersonAttribute();
}
}
关键字词:java,面向对象,继承