面向对象之入门代码(面向对象编程是什么)

package org.example;


import java.util.Scanner; // 修正分号

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        // 读取输入并创建分数对象
        Fraction a = new Fraction(in.nextInt(), in.nextInt());
        Fraction b = new Fraction(in.nextInt(), in.nextInt());

        // 输出原始分数
        a.print();
        b.print();

        // 加法运算
        a.plus(b).print();

        // 组合运算:a * b + 5/6
        a.multiply(b).plus(new Fraction(5, 6)).print();

        // 再次输出原始分数(验证是否被修改)
        a.print();
        b.print();

        in.close();
    }
}

// 示例 Fraction 类(需补充完整实现)
class Fraction {
    private int numerator;
    private int denominator;

    public Fraction(int numerator, int denominator) {
        if (denominator == 0) {
            throw new IllegalArgumentException("分母不能为0");
        }

        // 约分处理
        int gcd = gcd(Math.abs(numerator), Math.abs(denominator));
        this.numerator = numerator / gcd;
        this.denominator = denominator / gcd;

        // 确保分母为正数
        if (this.denominator < 0) {
            this.numerator = -this.numerator;
            this.denominator = -this.denominator;
        }
    }

    public void print() {
        System.out.println(this.numerator + "/" + this.denominator);
    }

    public Fraction plus(Fraction other) {
        int newNumerator = this.numerator * other.denominator + other.numerator * this.denominator;
        int newDenominator = this.denominator * other.denominator;
        return new Fraction(newNumerator, newDenominator);
    }

    public Fraction multiply(Fraction other) {
        int newNumerator = this.numerator * other.numerator;
        int newDenominator = this.denominator * other.denominator;
        return new Fraction(newNumerator, newDenominator);
    }

    // 求最大公约数的私有方法
    private int gcd(int a, int b) {
        while (b != 0) {
            int temp = b;
            b = a % b;
            a = temp;
        }
        return a;
    }

}


这个构造函数是不需要返回类型的。

根据参数的不同调用不同的函数。

成员变量需要用this在成员函数中调用。

如果一个类你想让他在所有文件中都能访问,定义为pulic,并且所在文件以其类名命名。

如果一个函数前面没有限定为private public,那么限定符是friendly,这个函数只能是该类所在包的其他类才能访问。如果想继续访问,那么只能import该函数的包进来。

如果不导入包,那么只能是包名.类名这样使用全名。

装父类的容器,也可以装改父类的子类。

而且子类对象赋值给父类的时候,叫向上造型。







Java是单根结构。都是obejct继承的。






package org.面向对象;


import java.util.HashMap;
import java.util.Scanner;

public class Game {
    private Room currentRoom;

    private HashMap<String, Hanlder> handlers = new HashMap<>();

    public Game()
    {
        handlers.put("go", new HandlerGo(this));
        handlers.put("bye", new HandlerBye(this));
        handlers.put("help", new HandlerHelp(this));
        System.out.println("Handlers: " + handlers);  // 调试输出
        createRooms();
    }

    private void createRooms()
    {
        Room outside, lobby, pub, study, bedroom;

        //	制造房间
        outside = new Room("城堡外");
        lobby = new Room("大堂");
        pub = new Room("小酒吧");
        study = new Room("书房");
        bedroom = new Room("卧室");

        // 初始化房间的出口
        outside.setExit("east", lobby);
        outside.setExit("south", pub);
        outside.setExit("west", study);

        lobby.setExit("west", outside);
        lobby.setExit("up", study);

        pub.setExit("north", outside);
        study.setExit("east", outside);
        study.setExit("south", bedroom);
        study.setExit("down", pub);
        bedroom.setExit("east", study);
        bedroom.setExit("north", lobby);



        currentRoom = outside;  //	从城堡门外开始
    }

    // 封装房间出口初始化逻辑

    private void printWelcome() {
        System.out.println();
        System.out.println("欢迎来到城堡!");
        System.out.println("这是一个超级无聊的游戏。");
        System.out.println("如果需要帮助,请输入 'help' 。");
        System.out.println();
        hint();
    }

    private void hint() {
        System.out.println(currentRoom.getExitDesc()) ;
    }

    // 以下为用户命令

    public void goRoom(String direction)
    {
        Room nextRoom = currentRoom.getNextRoom(direction);

        if (nextRoom == null) {
            System.out.println("那里没有门!");
        }
        else {
            currentRoom = nextRoom;
            hint();
        }

    }

    public void play() {
        while (true) {
            System.out.println(currentRoom.description);
            System.out.print("> ");
            Scanner in = new Scanner(System.in);
            String line = in.nextLine();
            String[] words = line.split(" ");
            String value = "";
            if(words.length > 1) {
                value = words[1];
            }
            else {
                value = words[0];
            }
            Hanlder hanlder = handlers.get(words[0]);
            System.out.println("Input command: " + words[0]);
            System.out.println("Handlers map: " + handlers);
            if(hanlder != null) {
                hanlder.doCmd(value);
                if(hanlder.isBye(value)) {
                    break;
                }
            } else{

                System.out.println("无效的命令!");
                this.printWelcome();
            }
        }
    }

    public static void main(String[] args) {

        Game game = new Game();
        game.printWelcome();

        game.play();


    }

}


 Hanlder hanlder = handlers.get(words[0]);
            System.out.println("Input command: " + words[0]);
            System.out.println("Handlers map: " + handlers);
            if(hanlder != null) {
                hanlder.doCmd(value);
                if(hanlder.isBye(value)) {
                    break;
                }
            } else{

                System.out.println("无效的命令!");
                this.printWelcome();
            }

这里hanlder.isBye如果想调用到正确的子类hanlderBye的isBye,那么子类重载如下,记得添加 @Override,函数参数也要和父类一致。

package org.面向对象;

public class HandlerBye extends Hanlder{

    public HandlerBye(Game game) {
        super(game);
    }

    @Override
    public boolean isBye(String cmd)
    {
        return true;
    }
}
--------------------------以上代码主要是想调用相应的辅助类,而不是硬编码,这样有新的命令只需向handler里添加新的
辅助类,比如HandlerWW等。

    public Game()
    {
        handlers.put("go", new HandlerGo(this));
        handlers.put("bye", new HandlerBye(this));
        handlers.put("help", new HandlerHelp(this));
        System.out.println("Handlers: " + handlers);  // 调试输出
        createRooms();
    }
辅助类定义如下
package org.面向对象;

public abstract class Hanlder {

    protected Game game;

    public Hanlder(Game game){
        this.game = game;
    }
    public void doCmd(String cmd){}
    public boolean isBye(String cmd){
        return false;
    }

}
-----------------------------------
package org.面向对象;

public class HandlerBye extends Hanlder{

    public HandlerBye(Game game) {
        super(game);
    }

    @Override
    public boolean isBye(String cmd)
    {
        return true;
    }
}
-----------------------------
package org.面向对象;

public class HandlerGo extends Hanlder {
    public HandlerGo(Game game) {
        super(game);
    }

    @Override
    public void doCmd(String word)
    {
        game.goRoom(word);
    }
}
--------------------------
package org.面向对象;

public class HandlerHelp extends Hanlder {

    public HandlerHelp(Game game) {
        super(game);

    }

    @Override
    public void doCmd(String word) {
        System.out.println("Help 命令");
        System.out.println("  help - 显示帮助");
        System.out.println("  bye - 退出游戏");
        System.out.println("  look - 显示当前房间");
        System.out.println("  go <方向> - 移动到指定方向的房间");
        System.out.println("  take <物品> - 从房间中取走物品");
        System.out.println("  drop <物品> - 丢弃物品");
    }

}
原文链接:,转发请注明来源!