zoukankan      html  css  js  c++  java
  • java_抽象类应用

       本例子通过一个实例来具体阐述抽象类的应用,首先一个抽象类Person2,里面定义了一些人的共有属性(年龄,姓名),和抽象方法want(),want()方法来具体实现不同的人的需求(学生想要成绩,工人想要工资)。接下来student类和worker类继承Person类,并且实现自己想要的want(),但是人的共有属性(年龄,姓名)就不要再次实现了,这样就大大减少了代码量。

        还要记住不要去继承一个已经实现好的抽象类。

        

     1 package com.test;
     2 
     3 abstract class Person2{
     4     private int age;
     5     private String name;
     6     public Person2(int age,String name) {
     7         this.age = age;
     8         this.name = name;
     9     }
    10     public int getAge() {
    11         return age;
    12     }
    13     public void setAge(int age) {
    14         this.age = age;
    15     }
    16     public String getName() {
    17         return name;
    18     }
    19     public void setName(String name) {
    20         this.name = name;
    21     }
    22     public abstract void want();
    23 }
    24 
    25 class Student2 extends Person2{
    26     
    27 
    28     private int score;
    29 
    30     public Student2(int age, String name,int score) {
    31         super(age, name);
    32         this.score = score;
    33         
    34     }
    35     public int getScore() {
    36         return score;
    37     }
    38 
    39     public void setScore(int score) {
    40         this.score = score;
    41     }
    42 
    43     @Override
    44     public void want() {
    45         System.out.println("姓名: "+getName()+"  年龄:"+getAge()+"  成绩: "+getScore());
    46     }
    47     
    48 }
    49 
    50 class Worker2 extends Person2{
    51 
    52     private int money;
    53     public void setMoney(int money) {
    54         this.money = money;
    55     }
    56     public int getMoney() {
    57         return money;
    58     }
    59     
    60     public Worker2(int age, String name,int money) {
    61         super(age, name);
    62         this.money = money;
    63     }
    64 
    65     @Override
    66     public void want() {
    67         System.out.println("姓名: "+getName()+"  年龄:"+getAge()+"  工资: "+getMoney());
    68     }
    69     
    70 }
    71 
    72 public class AbsDetail {
    73 
    74     public static void main(String[] args) {
    75         Student2 s = new Student2(10, "小明", 100);
    76         s.want();
    77         
    78         Worker2 w = new Worker2(35, "大明", 1000000);
    79         w.want();
    80     }
    81 
    82 }

         运行结果:

    姓名: 小明  年龄:10  成绩: 100
    姓名: 大明  年龄:35  工资: 1000000
  • 相关阅读:
    [转]create a basic sql server 2005 trigger to send email alerts
    SDUT OJ 2783 小P寻宝记
    联想杨元庆:互联网不包治百病 概念被夸大
    【Stackoverflow好问题】Java += 操作符实质
    poj 2513 Colored Sticks (trie 树)
    Nginx基础教程PPT
    POJ 1753 Flip Game (DFS + 枚举)
    poj 3020 Antenna Placement (最小路径覆盖)
    Unable to boot : please use a kernel appropriate for your cpu
    HDU 2844 Coins (多重背包)
  • 原文地址:https://www.cnblogs.com/UniqueColor/p/5712221.html
Copyright © 2011-2022 走看看