美文网首页
Java学习笔记 - 第010天

Java学习笔记 - 第010天

作者: 迷茫o | 来源:发表于2016-12-09 20:14 被阅读0次

    每日要点

    继承

    继承 : 从已有的类创建新类的过程就是继承
    提供继承信息的称为父类
    得到继承信息的称为子类
    extends - 扩展(子类除了父类的特性之外还有扩充自己特有的东西)
    例子:实现Person类,派生出Student、Teacher
    Person类:

    public class Person {
        // protected - 对子类相当于公开,对其他类相当于私有
        protected String name;
        protected int age;
        
        public Person(String name, int age) {
            this.age = age;
            this.name = name;
        }
        
        public void eat() {
            System.out.println(name + "正在吃饭.");
        }
        
        public void play(String gameName) {
            System.out.println(name + "正在玩" +gameName);
        }
        
        public void watchAV() {
            if (age >= 18) {
                System.out.println(name + "正在观看岛国动作片.");
            }
            else {
                System.out.println(name + "年龄未满18岁不能看.");
            }
        }
    }
    

    学生类:

    public class Student extends Person{
        private String classCode;
        
        public Student(String name, int age) {
            super(name, age);
        }
        
        public void study(String courseName) {
            System.out.println(name + "正在" + classCode + "班学习" + courseName + ".");
        }
        
        public void setClassCode(String classCode) {
            this.classCode = classCode;
        }
    }
    

    老师类:

    public class Teacher extends Person{
        private String title;
        
        public Teacher(String name, int age, String title) {
            super(name, age);
            this.title = title;
        }
        
        public void teach(String courseName) {
            System.out.println(name + title +"正在教" + courseName + ".");
        }
    }
    

    测试类:

    public class Test01 {
        public static void main(String[] args) {
            // 子类跟父类之间是一种is-a关系
            // 把子类对象赋值给父类变量没有任何问题
            Person stu1 = new Student("王大锤", 15);
            Person stu2 = new Student("王尼玛", 13);
            Person teacher = new Teacher("爱迪生", 36, "叫兽");
            ((Student) stu2).setClassCode("JavaEE 1601");
            stu1.eat();
            stu1.play("LOL");
            stu2.watchAV();
            ((Student) stu2).study("Java");
            teacher.eat();
            teacher.play("斗地主");
            teacher.watchAV();
            ((Teacher) teacher).teach("JavaEE企业级开发");
            // 类型转换异常
    //      ((Teacher) stu1).teach("高等数学");
        }
    }
    

    protected

    protected - 对子类相当于公开,对其他类相当于私有

    子类和父类

    子类跟父类之间是一种is-a关系
    把子类对象赋值给父类变量没有任何问题

    类型转换异常
    ((Teacher) stu1).teach("高等数学");

    花括号

    一对花括号就构成了一个作用域(scope)
    在某个作用域中定义的变量只在该作用域生效

    昨天作业讲解

    • **1.Craps赌博游戏 - 面向对象 **
      **两颗色子 - **
      第一次:
      玩家摇出 7 和11 玩家胜 2 3 或12 庄家胜 其他点数 游戏继续
      玩家再摇
      如果摇出7点 庄家胜 如果摇出了第一次的点数 玩家胜 其他情况 游戏继续

    骰子类:

    /**
     * 色子
     * @author Kygo
     *
     */
    public class Dice {
        private int face;
        
        /**
         * 摇色子
         */
        public void roll() {
            face = (int) (Math.random() * 6 + 1);
        }
        
        /**
         * 获取色子点数
         * @return 点数
         */
        public int getFace() {
            return face;
        }
    }
    

    玩家类:

    /**
     * 玩家
     * @author Kygo
     *
     */
    public class Player {
        private String name;
        private int money;
        private int bet;
        
        /**
         * 构造器:默认玩家有1000元资产
         * @param name 玩家姓名
         */
        public Player(String name) {
            this(name, 1000);
        }
        
        /**
         * 构造器
         * @param name 玩家姓名
         * @param money 玩家资产
         */
        public Player(String name, int money) {
            this.name = name;
            this.money = money;
        }
        
        /**
         * 获取玩家姓名
         * @return 玩家姓名
         */
        public String getName() {
            return name;
        }
        
        /**
         * 获取玩家资产
         * @return 玩家资产
         */
        public int getMoney() {
            return money;
        }
        
        /**
         * 设置赌注
         * @param bet 赌注金额
         */
        public void setBet(int bet) {
            this.bet = bet;
        }
        
        /**
         * 赢
         */
        public void win() {
            money += bet;
        }
        
        /**
         * 输
         */
        public void lose() {
            money -= bet;
        }
    }
    

    Craps游戏类:

    /**
     * Craps游戏
     * @author Kygo
     *
     */
    public class CrapsGame {
        private Dice dice1 = new Dice();        // 色子1
        private Dice dice2 = new Dice();        // 色子2
        private Player player;                      // 游戏玩家
        private boolean firstRoll;                  // 是不是第一次摇色子
        private boolean roundOver;          // 当前轮次是否结束
        private int firstPoint;                     // 第一次摇出的点数
        private String info;                            // 游戏提示信息
        
        public CrapsGame() {
            this.reset();
        }
        
        /**
         * 摇两颗色子
         */
        public void rollTwoDice() {
            dice1.roll();
            dice2.roll();
            int currentPoint = dice1.getFace() + dice2.getFace();
            info = "玩家摇出了" + currentPoint + "点.";
            if (firstRoll) {
                switch (currentPoint) {
                case 7: case 11:
                    info += "玩家胜!";
                    player.win();
                    roundOver = true;
                    break;
                case 2: case 3: case 12:
                    info += "庄家胜!";
                    player.lose();
                    roundOver = true;
                    break;
                default:
                    firstPoint = currentPoint;
                    firstRoll = false;
                }
            }
            else {
                if (currentPoint == firstPoint) {
                    info += "玩家胜!";
                    player.win();
                    roundOver = true;
                }
                else if (currentPoint == 7) {
                    info += "庄家胜!";
                    player.lose();
                    roundOver = true;
                }
            }
        }
        
        /**
         * 获取当前轮次是否分出胜负
         * @return 分出胜负返回true否则返回false
         */
        public boolean isRoundOver() {
            return roundOver;
        }
        
        /**
         * 重置游戏
         */
        public void reset() {
            firstRoll = true;
            roundOver = false;
        }
        
        /**
         * 获取游戏提示信息
         * @return 提示信息
         */
        public String getInfo() {
            return info;
        }
        
        /**
         * 设置游戏玩家
         * @param player 玩家对象
         */
        public void setPlayer(Player player) {
            this.player = player;
        }
    }
    

    测试游戏类:

    public class CrapsGameRunner {
    
        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            // 创建游戏对象
            CrapsGame game = new CrapsGame();
            // 创建玩家对象
            Player player = new Player("王大锤");
            // 设置游戏玩家
            game.setPlayer(player);
            do {
                // 显示玩家资产
                System.out.println(player.getName() + "的总资产为: ¥" + player.getMoney() + "元.");
                // 下注
                int bet;
                do {
                    System.out.print("请下注: ");
                    bet = input.nextInt();
                } while (bet <= 0 || bet > player.getMoney());
                player.setBet(bet);
                // 开始摇色子
                while (!game.isRoundOver()) {
                    game.rollTwoDice();
                    System.out.println(game.getInfo());
                }
                // 一轮游戏结束后重置游戏
                game.reset();
            } while (player.getMoney() > 0);
            // 玩家钱输光了游戏结束
            System.out.println(player.getName() + "已经破产. 游戏结束!");
            input.close();
        }
    }
    
    • 2.设计ATM - 面向对象
      银行账户类:
    /**
     * 银行账户
     * @author Kygo
     *
     */
    public class Account {
        private String id;
        private String password;
        private double balance;
        
        /**
         * 构造器
         * @param id 账户ID
         * @param password 初始密码
         * @param blance 初始余额
         */
        public Account(String id, String password, double blance) {
            this.id = id;
            this.password = password;
            this.balance = blance;
        }
        
        /**
         * 验证身份是否有效
         * @param password 密码
         * @return 密码匹配返回true否则返回false
         */
        public boolean isValid(String password) {
            return this.password.equals(password);
        }
        
        /**
         * 存钱
         * @param money 存款金额
         */
        public void deposit(double money) {
            balance += money;
        }
        
        /**
         * 取款
         * @param money 取款金额
         * @return 取款成功返回true,余额不足返回false
         */
        public boolean withdraw(double money) {
            if (money <= balance) {
                balance -= money;
                return true;
            }
            return false;
        }
        
        /**
         * 获得账号
         * @return 账号
         */
        public String getId() {
            return id;
        }
        
        /**
         * 查询余额
         * @return 余额
         */
        public double getBalance() {
            return balance;
        }
        
        /**
         * 设置密码
         * @param password 密码
         */
        public void setPassword(String password) {
            this.password = password;
        }
    }
    

    ATM类:

    /**
     * 自动柜员机
     * @author Kygo
     *
     */
    public class ATM {
        private Account currentAccount;
        
        // 用一个数组来模拟银行的数据库系统 预先保存若干个银行账户
        private Account[] accountArray = {
            new Account("11223344", "123123", 1200),
            new Account("22334455", "123456", 50),
            new Account("33445566", "888888", 9999999)
        };
        
        /**
         * 读卡
         * @param id 银行账户ID
         * @return 读卡成功返回true否则返回false
         */
        public boolean readCard(String id) {
            for (Account account : accountArray) {
                if (account.getId().equals(id)) {
                    currentAccount = account;
                    return true;
                }
            }
            return false;
        }
        
        /**
         * 验证身份
         * @param password 密码
         * @return 验证通过返回true否则返回false
         */
        public boolean verify(String password) {
            if (currentAccount != null) {
                return currentAccount.isValid(password);
            }
            return false;
        }
        
        /**
         * 查询余额
         * @return 当前账号余额
         */
        public double showBalance() {
            return currentAccount.getBalance();
        }
        
        /**
         * 存钱
         * @param money 存入金额
         */
        public void deposit(int money) {
            currentAccount.deposit(money);
        }
        
        /**
         * 取钱
         * @param money 取款金额
         * @return 取款成功返回ture否则返回false
         */
        public boolean withdraw(int money) {
            return currentAccount.withdraw(money);
        }
        
        /**
         * 修改密码
         * @param newPassword 新密码
         */
        public void changePassword(String newPassword) {
            currentAccount.setPassword(newPassword);
        }
        
        /**
         * 取卡
         */
        public void quitCard() {
            currentAccount = null;
        }
        
        /**
         * 转账
         * @param otherId 转入账号
         * @param money 转账金额
         * @return 转账成功返回true否则返回false
         */
        public boolean transfer(String otherId, double  money) {
            for (Account account : accountArray) {
                if (account.getId().equals(otherId)) {
                    Account otherAccount = account;
    //              if (currentAccount.getBalance() >= money) {
                    if (currentAccount.withdraw(money)) {           
                        otherAccount.deposit(money);
                        return true;
                    }
                    else {
                        return false;
                    }
                }
            }
            return false;
        }
    }
    

    测试类:

    public class ATMTest {
    
        public static void main(String[] args) {
            Scanner input = new Scanner(System.in); 
            ATM atm = new ATM();
            boolean isRunning = true;
            while(isRunning) {
                System.out.println("欢迎使用中国贱人银行ATM机.");
                System.out.print("请插入银行卡: ");
                String id = input.next();
                if (atm.readCard(id)) {
                    int counter = 0;
                    boolean isCorrect = false;
                    do {
                        counter += 1;
                        System.out.print("请输入密码: ");
                        String password = input.next();
                        isCorrect = atm.verify(password);
                    } while (counter < 3 && !isCorrect);
                    if (isCorrect) {
                        boolean flag = true;
                        while (flag) {
                            System.out.println("1.查询余额");
                            System.out.println("2.存款");
                            System.out.println("3.取款");
                            System.out.println("4.转账");
                            System.out.println("5.修改密码");
                            System.out.println("6.退卡");
                            int choice;
                            do {
                                System.out.print("请选择: ");
                                choice = input.nextInt();
                            } while (choice < 1 || choice >6);
                            switch (choice) {
                            case 1:
                                System.out.println("账户余额: " + atm.showBalance());
                                break;
                            case 2: {
                                // 一对花括号就构成了一个作用域(scope)
                                // 在某个作用域中定义的变量只在该作用域生效
                                System.out.print("请放入钞票: ");
                                int money = input.nextInt();
                                atm.deposit(money);
                                System.out.println("存款成功!");
                                break;
                            }
                            case 3: {
                                System.out.print("请输入或选择取款金额: ");
                                int  money = input.nextInt();
                                if (atm.withdraw(money)) {
                                    System.out.println("请取走你的钞票.");
                                }
                                else {
                                    System.out.println("余额不足!");
                                }
                                break;
                            }
                            case 4: {
                                System.out.print("请输入转入账号: ");
                                String otherId = input.next();
                                System.out.print("请输入转账金额: ");
                                double money = input.nextDouble();
                                if (atm.transfer(otherId, money)) {
                                    System.out.println("转账成功!");
                                }
                                else {
                                    System.out.println("转账失败,请检查转入账号和账户余额是否正确.");
                                }
                                break;
                            }
                            case 5:
                                System.out.print("请输入新密码: ");
                                String newPwd = input.next();
                                System.out.print("请再输入一次: ");
                                String rePwd = input.next();
                                if (newPwd.equals(rePwd)) {
                                    atm.changePassword(newPwd);
                                    System.out.println("密码已修改.");
                                }
                                else {
                                    System.out.println("两次密码不一致.");
                                }
                                break;
                            case 6:
                                System.out.println("请取走你的卡.");
                                flag = false;
                                break;
                            }
                        }
                    }
                    else {
                        System.out.println("输入密码错误次数超过3次,你的卡已经被回收.");
                    }
                }
            }
            input.close();
        }
    }
    

    作业

    • 1.描述宠物 使用继承 派生出猫、狗之类的
      宠物类:
    public class Pet {
        protected String name;
        protected boolean isAdult;
        protected String variety;
        
        public Pet(String name,String variety, boolean isAdult) {
            this.name = name;
            this.variety = variety;
            this.isAdult = isAdult;
        }
        public void sleep() {
            System.out.println("宠物" + name + "在睡觉.");
        }
        
        public void eat() {
            System.out.println("宠物" + name + "在吃东西.");
        }
        
        public void mating() {
            if (isAdult) {
                System.out.println("宠物" + name + "正在交配.");
            }
            else {
                System.out.println("宠物" + name + "还未成年.");
            }
        }
    }
    

    猫类:

    public class Cat extends Pet {
        private String yell;
        
        public Cat(String name, String variety, boolean isAdult, String yell) {
            super(name, variety,isAdult);
            this.yell = yell;
        }
        
        public void catchMouse() {
            System.out.println(variety + name + "在抓老鼠.");
        }
        
        public void purr() {
            System.out.println(variety + name + "在叫: " + yell);
        }
    }
    

    相关文章

      网友评论

          本文标题:Java学习笔记 - 第010天

          本文链接:https://www.haomeiwen.com/subject/gjkymttx.html