java继承性总结
作者:互联网
1、定义Person类和Student类,如果想要Student继承Person类的属性/方法,需要将 class Student(){}写成 class Student extends Person(){};
2、当Person中定义了private的属性,则Student继承后也无法直接访问;需要class Person(){} 里提供get和set方法;相当于 Student可以继承Person中的属性/方法,但无法直接用Person中的属性,需要Student提供get/set方法(继承时,被调用的为私有的时相当于 保险箱里有钱,但需要通过努力或方法,才能使用这里面的钱)
示例:
Person类
package com.test.p4;
public class Person {
String name;
private int age;
// 创建构造函数
public Person(){
}
public Person(String name, int age){
this.name = name;
this.age = age;
}
// 定义get和set方法
public int getAge(){
return age;
}
public void setAge(int age){
this.age = age;
}
public void eat(){
System.out.println("person吃");
}
public void sleep(){
System.out.println("person睡");
}
public void wear(){
System.out.println("穿");
}
}
Student类
package com.test.p4;
import javax.swing.*;
import java.awt.dnd.DragGestureEvent;
public class Student extends Person{
String major; //专业
public Student(){
}
public Student(String name, int age, String major){
this.name = name;
setAge(23);
this.major = major;
}
public void study(){
System.out.println("student学习专业课");
}
public void print(){
System.out.println("name: " + name + " age: " + getAge());
}
}
主函数测试类
package com.test.p4;
public class ExtendsTest {
public static void main(String[] args) {
Student s1 = new Student();
s1.print();
s1.setAge(55);
System.out.println(s1.getAge());
}
}
标签:总结,java,name,age,Person,void,Student,继承性,public 来源: https://blog.csdn.net/weixin_46932303/article/details/115427216