Java|java extends继承和override重写的用法

Java|java extends继承和override重写的用法

/**
* 测试extends继承 java三大属性之一
* 测试override重写
* 测试final修饰
*/
class Children{
String name;
int age ;
Children friend;
public void pn(){
System.out.println(name);

【Java|java extends继承和override重写的用法】
class Student1{
String name;
int age ;
Children friend;
public void pn(){
System.out.println(name);

//属性方法和Children一致
String major;
public void pm(){
System.out.println(major);


class Student2 extends Children{
//继承了Children类的所有内容 name age pn friend
public void pa(){
System.out.println(age);
//直接调用继承过来的的age
pn();

String major;
public Student2(String nameint ageString major){
this.name = name;
this.age = age;
this.major = major;

public class TestExtends {
public static void main(String[
args) {
Student2 s1 = new Student2(\"a\"10\"Math\");
System.out.println(s1 instanceof Student2);
//instanceof运算符 判断对象s1是否属于类Student2
System.out.println(s1 instanceof Children);
//判断s1是否属于父类Children 结果true
Student1 s2 = new Student1();
System.out.println(s2 instanceof Student1);
//System.out.println(s2 instanceof Children);报错 结果false



class Student3{
//不写明extends 默认 Student3 extends java.lang.Object

class Student4 extends Children{
Student4 friend;
//重写override 把Children类里的friend属性重定义 , 父类原始属性不受影响
//重写的范围小于等于父类的原型 父类的friend是Children型 子类是Student4小于等于Children
short age;
//父类age是int 子类age是short小于等于int
public void pn(){
System.out.println(\"The name is \"+name);

//对原方法重写 更改内容

final class Student5 extends Children{
//final修饰的类不能再往下继承 常见String Math类都是final
final int age =10;
//继承的属性可以final 不可再修改 不影响父类age
final public void pn(){
System.out.println(\"\"+name+age);

//final的方法不可重写 可以重载overload