zoukankan      html  css  js  c++  java
  • java多态范例 无敌

    package com.learnjava.gj.oop;

    /**

    • USER : JACK
    • DATE : 2021/11/20 19:36
    • DESC : Person类是父类

    */
    public class Person {
    //成员变量 挂接到实例上 讲实例属性进行封装,通过特定方法进行访问
    private String name;
    private int age;

    //构造方法
    public Person(String name,int age){
        this.name = name;
        this.age = age;
    }
    
    //getter and setter
    
    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 showInfo(){
        System.out.println(this.name + " is "+this.age+" years old!");
    }
    

    }

    
    

    Student

    package com.learnjava.gj.oop;

    /**

    • USER : JACK

    • DATE : 2021/11/20 19:40

    • DESC :学生子类 继承Person类部分方法和属性
      */
      public class Student extends Person{
      //独有属性
      private String school;

      //构造方法
      public Student(String name,int age,String school){
      super(name,age);
      this.school = school;
      }
      @Override
      //重写父类showInfo()方法
      public void showInfo(){
      System.out.println(this.getName() + " is "+this.getAge()+" years old!,学校是:"+this.school);
      }
      }

    
    MainTest
    

    package com.learnjava.gj.oop;

    /**

    • USER : JACK
    • DATE : 2021/11/20 19:47
    • DESC :
      */
      public class MainTest {
      public static void showInfoP(Person p){
      if(p instanceof Student){
      p = (Student) p;
      p.showInfo();
      }else{
      p.showInfo();
      }
      }
      public static void main(String[] args) {
      Student p = new Student("jack",12,"北高");
      Person p1 = new Person("bob",23);
      showInfoP(p1);
      showInfoP(p);
      }

    }

  • 相关阅读:
    Postfix邮件服务器搭建及配置
    利用linux漏洞进行提权
    NFS部署和优化
    LAMP环境搭建
    Apache2.4.6服务器安装及配置
    linux笔记_防止ddos攻击
    CentOS6.5恢复误删除的文件
    linux计划任务
    linux软连接和硬链接
    linux用户和用户组的基本操作
  • 原文地址:https://www.cnblogs.com/lihuafeng/p/15582434.html
Copyright © 2011-2022 走看看