师从鬼谷 2022-03-30 19:31 采纳率: 100%
浏览 36
已结题

求优化一下关于JAVA多态的问题

img

img


我看每个对象都要写一遍输出代码很麻烦,有没有一种方法可以只要写一遍,再从各个对象调用数据就好的方法。

  • 写回答

3条回答 默认 最新

  • Tomshidi 2022-03-30 21:32
    关注

    使用设计模式应该能让代码看起来更优雅,但是你不一定能理解。所以暂且就写成下面这样吧。

    public abstract class Student {
        protected int xh;
    
        protected String xm;
    
        protected char xb;
    
        protected double sg;
    
        public void information() {
            System.out.println("学号:" + xh);
            System.out.println("姓名:" + xm);
            System.out.println("性别:" + xb);
            System.out.println("身高:" + sg);
            System.out.println("--------------------");
        }
    }
    
    public class ZhangSan extends Student {
    
        public ZhangSan() {
            this.xh = 110;
            this.xm = "张三";
            this.xb = '男';
            this.sg = 1.85;
        }
    }
    
    public class LiSi extends Student {
    
        public LiSi() {
            this.xh = 120;
            this.xm = "李四";
            this.xb = '女';
            this.sg = 1.65;
        }
    }
    
    public class StartMain {
        public static void main(String[] args) {
            new ZhangSan().information();
            new LiSi().information();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 4月8日
  • 已采纳回答 3月31日
  • 创建了问题 3月30日

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献