Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
17 kB
3
Indexable
Never
javacore.organization.oop

1. classandobject
    1.1. accessmodifiers
        1.1.1.Main

/*
 * Bien trong Java co hai loai: Bien tinh (static) va Bien phi tinh(non-static) 
 * Bien tinh (static) thuoc ve lop chu khong phai mot doi tuong. Cac bien tinh chi khoi tao mot lan va chia se chung cho tat ca doi tuong cua lop. Chung co the truy cap truc tiep ma khong can tao doi tuong
 * Bien phi tinh thuoc ve tung doi tuong cu the. Moi doi tuong cua lop se tao ra mot ban sao rieng cua bien phi tinh  cac doi tuong khong chia se gia tri cua bien nay
 * 
 * Tu khoa static dung de chi thuoc tinh hoac phuong thuc thuoc ve lop chu khong phai mot doi tuong cu the
 */

/*
 * Doi voi arributes, methods, constructors thi co 4 pham vi truy cap:
 * 
 * 1. public: co the truy cap tu bat ky noi nao: cac lop khac trong cung package hoac tu ben ngoai package
 * 2. private: chi co the truy cap tu ben trong cung lop chua chung, cac lop khac khong the truy cap truc tiep vao thanh phan nay
 * 3. protected: co the truy cap tu ben trong cung lop chua chung, tu lop con cua lop chua va tu cac lop trong cung package. Khong the duoc truy cap tu ben ngoai package neu khong co quan he ke thua
 * 4. default (khong co tu khoa): pham vi mac dinh chi gioi han trong cung package
 */

public class Main {
	public static int staticVal;
	public int nonStaticVal;
	
	public static void staticMethod(){
		System.out.println("static method");
	}
	
	public void instanceMethod(){
		System.out.println("instance method");
	}
	
	static class staticClass{
		static int x;
		static int y;
		
		static void init(int ix, int iy){
			x = ix;
			y = iy;
		}
	}
	
	class instanceClass{
		int x;
		int y;
		
		void init(int ix, int iy){
			x = ix;
			y = iy;
		}
	}
	
	public static void main(String[] args) {
		staticVal = 1;
		Main test = new Main();
		test.staticVal = 2;
		test.nonStaticVal = 1;
		System.out.println(staticVal);
		System.out.println(test.nonStaticVal);
		
		staticMethod();
		test.instanceMethod();
		
		staticClass sc = new staticClass();
		sc.init(2, 3);
		staticClass sc2 = new staticClass();
		System.out.println(sc2.x);
		instanceClass ic = test.new instanceClass();
		ic.init(3, 4);
		System.out.println(ic.x);
		
	}
}

#############################################

    1.2. classes
        1.2.1. innerclasses
            1.2.1.1. GearBox

import java.util.ArrayList;

public class Gearbox {
    private ArrayList<Gear> gears;
    private int maxGears;
    private int currentGear = 0;
    private boolean clutchIsIn;

    public Gearbox(int maxGears) {
        this.maxGears = maxGears;
        this.gears = new ArrayList<>();
        Gear neutral = new Gear(0, 0.0);
        this.gears.add(neutral);
    }

    public void operateClutch(boolean in) {
        this.clutchIsIn = in;
    }

    public void addGear(int number, double ratio) {
        if (number > 0 && number <= maxGears) {
            this.gears.add(new Gear(number, ratio));
        }
    }

    public void changeGear(int newGear) {
        if (newGear >= 0 && newGear < this.gears.size() && this.clutchIsIn) {
            this.currentGear = newGear;
            System.out.println("Gear " + newGear + " selected.");
        } else {
            this.currentGear = 0;
            System.out.println("Grind!");
        }
    }

    public double wheelSpeed(int revs) {
        if (clutchIsIn) {
            System.out.println("Scream!");
            return 0.0;
        }

        return revs * gears.get(currentGear).getRatio();
    }

    public class Gear {
        private int gearNumber;
        private double ratio;

        public Gear(int gearNumber, double ratio) {
            this.gearNumber = gearNumber;
            this.ratio = ratio;
        }

        public double getRatio() {
            return ratio;
        }

        public double driveSpeed(int revs) {
            return revs * this.ratio;
        }
    }
}

##############################

            1.2.1.2. Main

public class Main {
    public static void main(String[] args) {
        Gearbox mcLaren = new Gearbox(6);
        Gearbox.Gear first = mcLaren.new Gear(1, 12.3);
//        Gearbox.Gear second = new Gearbox.Gear(2, 15.4);
//        Gearbox.Gear third = new mcLaren.Gear(3, 17.8);
        System.out.println(first.driveSpeed(1000));
    }
}

##############################

        1.2.2. myclasses
            1.2.2.1. Car

public class Car {
    private int doors;
    private int wheels;
    public String model;
    private String color;
    private String engine;

    public void setModel(String model) {
        String validModel = model.toLowerCase();
        if (validModel.equals("carrera") || validModel.equals("commodore")) {
            this.model = model;
        } else {
            this.model = "Unknown";
        }
    }

    public String getModel() {
        return this.model;
    }
}

#######################

            1.2.2.2. House

class House {
    String color;

    public House(String color) {
        this.color = color;
    }

    public String getColor() {
        return color;
    }

    void setColor(String color) {
        this.color = color;
    }
}

class Account {

    private long balance;
    private String ownerName;
    private boolean locked;

    public long getBalance() {
        return balance;
    }

    public void setBalance(long balance) {
        this.balance = balance;
    }

    public String getOwnerName() {
        return ownerName;
    }

    public void setOwnerName(String ownerName) {
        this.ownerName = ownerName;
    }

    public boolean isLocked() {
        return locked;
    }

    public void setLocked(boolean locked) {
        this.locked = locked;
    }
}

##########################################

            1.2.2.3. Main

public class Main {
    public static void main(String[] args) {
        //classExample1();
        classExample2();
    }

    public static void classExample2() {
        /*
         * House la mot class, co the hieu nhu mot ban thiet ke
         *
         * new House("blue") la mot Object hoac Instance cua House va dang gan cho bien blueHouse hay noi cach khac
         * blueHouse la mot tham chieu (reference) den doi tuong trong bo nho
         */

        House blueHouse = new House("blue");
        House anotherHouse = blueHouse;
        System.out.println(blueHouse);
        System.out.println(anotherHouse);

        anotherHouse.setColor("red");
        System.out.println(blueHouse.getColor());
        System.out.println(anotherHouse.getColor());

        House greenHouse = new House("green");
        anotherHouse = greenHouse;
        System.out.println(blueHouse.getColor());
        System.out.println(anotherHouse.getColor());
        System.out.println(greenHouse.getColor());
    }

    public static void classExample1() {
        Car porsche = new Car();
        Car holden = new Car();
        porsche.setModel("Hehe");
        System.out.println("Model is " + porsche.getModel());
    }
}

#####################################

        1.2.3. old
            1.2.3.1. Main

public class Main {
	//Attributes
	static int x = 5;
	static int y;
	final int z = 10;
	
	//Khoi tao doi tuong
	public static class Point{
		public int x = 0;
		public int y = 0;
		
		//constructor
		public Point(int x, int y){
			this.x = x;
			this.y = y;
			//myStaticMethod();
		}
	}
	
	//Method
	static void myStaticMethod(){
		System.out.println("Static");
	}
	public void myPublicMethod(){
		System.out.println("Public");
	}
	//Doi voi Method:
	//Static: chi ra method nay c� the duoc truy cap ma khong can tao mot doi tuong cua class
	//public: chi co the truy cap boi cac doi tuong
	
	public static void main(String[] args) {
		//tao 1 object cua Main
		Main myObject = new Main();
		System.out.println(x);
		x = 40;
		y = 10;
		//myObject.z = 15;
		myStaticMethod();
		myObject.myPublicMethod();
		
		Point p = new Point(1,2);
		Object obj = new Object(4, 5);
	}
}

########################################

            1.2.3.2. Object

public class Object {
	public int x = 1;
	public int y = 3;
	
	//constructor
	public Object(int x, int y){
		this.x = x;
		this.y = y;
		Main.Point p = new Main.Point(x, y);
	}
}

########################################

2. enums
    2.1. Exercise

public class Exercise {

    public static void main(String[] args) {
        Robot robot = new Robot(0, 0, Direction.RIGHT);
        Move.moveRobot(robot, -2, 3);
    }
}

class Move {
    public static void moveRobot(Robot robot, int toX, int toY) {
        if (robot.getX() < toX) {
            if (robot.getDirection() == Direction.UP) {
                robot.turnRight();
            } else if (robot.getDirection() == Direction.LEFT) {
                robot.turnRight();
                robot.turnRight();
            } else if (robot.getDirection() == Direction.DOWN) {
                robot.turnLeft();
            }
        } else {
            if (robot.getDirection() == Direction.UP) {
                robot.turnLeft();
            } else if (robot.getDirection() == Direction.RIGHT) {
                robot.turnLeft();
                robot.turnLeft();
            } else if (robot.getDirection() == Direction.DOWN) {
                robot.turnRight();
            }
        }

        while (robot.getX() != toX) {
            robot.stepForward();
            System.out.println(robot.getX() + " " + robot.getY());
        }

        if (robot.getY() < toY) {
            if (robot.getDirection() == Direction.LEFT) {
                robot.turnRight();
            } else if (robot.getDirection() == Direction.RIGHT) {
                robot.turnLeft();
            }
        } else {
            if (robot.getDirection() == Direction.LEFT) {
                robot.turnLeft();
            } else if (robot.getDirection() == Direction.RIGHT) {
                robot.turnRight();
            }
        }

        while (robot.getY() != toY) {
            robot.stepForward();
            System.out.println(robot.getX() + " " + robot.getY());
        }
    }
}

//Don't change code below

enum Direction {
    UP(0, 1),
    DOWN(0, -1),
    LEFT(-1, 0),
    RIGHT(1, 0);

    private final int dx;
    private final int dy;

    Direction(int dx, int dy) {
        this.dx = dx;
        this.dy = dy;
    }

    public Direction turnLeft() {
        switch (this) {
            case UP:
                return LEFT;
            case DOWN:
                return RIGHT;
            case LEFT:
                return DOWN;
            case RIGHT:
                return UP;
            default:
                throw new IllegalStateException();
        }
    }

    public Direction turnRight() {
        switch (this) {
            case UP:
                return RIGHT;
            case DOWN:
                return LEFT;
            case LEFT:
                return UP;
            case RIGHT:
                return DOWN;
            default:
                throw new IllegalStateException();
        }
    }

    public int dx() {
        return dx;
    }

    public int dy() {
        return dy;
    }
}

class Robot {
    private int x;
    private int y;
    private Direction direction;

    public Robot(int x, int y, Direction direction) {
        this.x = x;
        this.y = y;
        this.direction = direction;
    }

    public void turnLeft() {
        direction = direction.turnLeft();
    }

    public void turnRight() {
        direction = direction.turnRight();
    }

    public void stepForward() {
        x += direction.dx();
        y += direction.dy();
    }

    public Direction getDirection() {
        return direction;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }
}

#######################################

    2.2. Main

public class Main {
	enum Level{
		LOW,
		MEDIUM,
		HIGH
	}

	public enum UserStatus {
		PENDING, ACTIVE, BLOCKED
	}

	public enum ChargeLevel {
		FULL(4, "green"),
		HIGH(3, "green"),
		MEDIUM(2, "yellow"),
		LOW(1, "red");

		private final int sections;
		private final String color;

		ChargeLevel(int sections, String color) {
			this.sections = sections;
			this.color = color;
		}

		public int getSections() {
			return sections;
		}

		public String getColor() {
			return color;
		}

		public static ChargeLevel findByNumberOfSections(int sections) {
			for (ChargeLevel value: values()) {
				if (value.sections == sections) {
					return value;
				}
			}
			return null;
		}
	}
	
	public static void main(String[] args) {
		Level myVar = Level.HIGH;
		System.out.println(myVar);

		Level myLevel = Level.valueOf("LOW");
		System.out.println(myLevel);

		UserStatus active = UserStatus.ACTIVE;
		System.out.println(active.name()); // ACTIVE
		UserStatus blocked = UserStatus.valueOf("BLOCKED");

		UserStatus[] statuses = UserStatus.values(); // [PENDING, ACTIVE, BLOCKED]
		for (UserStatus status : statuses) {
			System.out.println(status);
		}

		System.out.println(active.ordinal()); // 1 (starting with 0)
		System.out.println(UserStatus.BLOCKED.ordinal()); // 2

		System.out.println(active.equals(UserStatus.ACTIVE)); // true
		System.out.println(blocked == UserStatus.BLOCKED); // true

		/////////////////////////////////////////////////////////////////

		System.out.println(ChargeLevel.LOW.getSections()); // 1
		System.out.println(ChargeLevel.LOW.getColor()); // red

		System.out.println(ChargeLevel.findByNumberOfSections(2)); // MEDIUM

	}
}

##################################

    2.3. Test

enum Secret {
    STAR,
    CRASH,
    START,
    // ...
}
public class Test {

    public static void main(String[] args) {
        int counter = 0;

        // write your code here
        for (Secret secret : Secret.values()) {
            if (secret.toString().startsWith("STAR")) {
                counter++;
            }
        }

        System.out.println(counter);
    }

    public static boolean changeBalance(Account account, Operation operation, Long sum) {
        // write your implementation here
        if (operation == Operation.DEPOSIT) {
            account.setBalance(account.getBalance() + sum);
        } else {
            if (sum > account.getBalance()) {
                System.out.println("Not enough money to withdraw.");

                return false;
            } else {
                account.setBalance(account.getBalance() - sum);
            }
        }

        return true;
    }

    /* Do not change code below */
    enum Operation {
        /**
         * deposit (add) an amount into an Account
         */
        DEPOSIT,
        /**
         * withdraw (subtract) an amount from an Account
         */
        WITHDRAW
    }

    static class Account {

        private String code;
        private Long balance;

        public String getCode() {
            return code;
        }

        public Long getBalance() {
            return balance;
        }

        public void setBalance(Long balance) {
            this.balance = balance;
        }
    }
}

######################################

4. nestedclasses
    4.1. AnonymousClass

/*
Anonymous classes enable you to declare and instantiate a class at the same time.

An anonymous class always implements an interface or extends another class (concrete or abstract)
 */

public class AnonymousClass {

    private static String BYE_STRING = "Auf Wiedersehen!"; // static constant
    private String NON_STATIC_STRING = "Non-static string";

    public static void main(String[] args) {
        final String hello = "Guten Tag!"; // final local variable

        SpeakingEntity cat = new SpeakingEntity() {
            @Override
            public void sayHello() {
                System.out.println("Meow");
            }

            @Override
            public void sayBye() {
                System.out.println("Meow");
            }
        };

        SpeakingEntity englishSpeakingPerson = new SpeakingEntity() {

            @Override
            public void sayHello() {
                System.out.println(hello);
            }

            @Override
            public void sayBye() {
                System.out.println(BYE_STRING + " and " + new AnonymousClass().NON_STATIC_STRING);
            }
        };

        // In the body of an anonymous class, it is possible to capture variables from a context where it is defined:
        // an anonymous class can capture members of its enclosing class (the outer class);
        // an anonymous class can capture local variables that are declared as final or are effectively final (i.e. the variable is not changed but it doesn't have the final keyword).
        englishSpeakingPerson.sayHello();
        englishSpeakingPerson.sayBye();
    }
}

interface SpeakingEntity {

    void sayHello();

    void sayBye();

}

Leave a Comment