Quangkhoi1228 | Knowledge base
  • Về trang chủ
  • Lời nói đầu
  • Nhập môn lập trình web
    • Giáo trình
    • Class 01: Hello HTML!!!
    • Class 02: HTML: Comment, Text formatting, Attribute, Link
    • Class 03: HTML: Style, Inline/Block element, Image
    • Class 04: HTML: List, Table, Responsive
    • Class 05: Hello CSS!!!
    • Class 06: CSS: Flexbox, Layout
    • Class 07: Hello Javascript!!!
    • Class 08: JS: Operator, Expression, For/While Loop, Function
    • Class 09: JS: Search Function
    • Project 1: Layout Structure
    • Project 2: Search Function
    • Project 3: MVP
    • Review "Lập trình Frontend Website"
  • Lập trình Frontend Website
    • Class 01: Ôn tập HTML
    • Class 02: Thảo luận HTML
    • Class 03: Ôn tập CSS
    • Class 04: Chrome dev tools, CSS Box Model
    • Class 05: CSS: Position, Đơn vị đo
    • Class 06: CSS: hiệu ứng, responsive
    • Class 07: Thảo luận CSS
    • Class 08: Ôn tập JS
    • Class 09: JS: Mảng, Đối tượng, Biến tham chiếu và tham trị
    • Class 10: JS: Class, Pair programming
    • Class 11: JS: DOM, UI Rendering
  • Lập trình ReactJS
    • Class 01: Giới thiệu ReactJS
    • Class 01: Tạo dự án ReactJS mới
    • Class 02: ReactJS Component
    • Class 02: Import/Export component
    • Class 03: useState hook
    • Class 04: Project 1: UI cơ bản
    • Class 05: Render có điều kiện và danh sách
    • Class 06: useEffect hook
    • Class 07: Project 2: Xử lý user logic
    • Class 08: Project 3: Hoàn thiện dashboard
    • Class 09: Form và dữ liệu người dùng
    • Class 10: UseRef và thao tác với DOM
    • Class 11: Project 4: Xử lý form data
    • Class 12: Project 5: Hoàn thiện form data
    • Class 13: useMemo và useCallback
    • Class 14: Custom Hook
    • Class 15: Project 6: Hoàn thiện project
    • Class 16: Ôn tập
  • Lập trình NestJS
    • Class 01: Giới thiệu NestJS & Cài đặt dự án
    • Class 02: Routing, Controller và Dependency Injection
    • Class 03: Service và Data Validation
    • Class 04: Kết nối Database với TypeORM
    • Class 05: Quan hệ trong Database (OneToMany, ManyToOne) với TypeORM
    • Class 06: Middleware, Interceptor, Guard
    • Class 07: Authentication – JWT
    • Class 08: Authorization – Phân quyền
    • Class 09: File Upload & Configuration
    • Class 10: Giới thiệu WebSocket
    • Class 11: Project 1
    • Class 12: Project 2
    • Class 13: Project 3
    • Class 14: Project 4
    • Class 15: Project 5
    • Class 16: Project 6
  • Lập trình Java cơ bản
    • Class 01: Khai giảng
    • Class 02: Hello Java
    • Class 03: Biến và kiểu dữ liệu
    • Class 04: Toán tử và biểu thức
    • Class 05: Câu lệnh điều kiện
    • Class 06: Review 1
    • Class 07: Vòng lặp For
    • Class 08: Vòng lặp While / Do-while
    • Class 09: Java Method
    • Class 10: Review 2
    • Class 11: Java User Input
    • Class 12: Java File
    • Class 13: Final Exam 1
    • Class 14: Final Exam 2
    • Review "Lập trình OOP với Java"
  • Lập trình OOP với Java
    • Class 01: Hello OOP
    • Class 02: Class Attribute và Method
    • Class 03: Constructor, Modifier và Package
    • Class 04: Review 1
    • Class 05: Tính kế thừa và đa hình
    • Class 06: Tính trừu tượng và đóng gói
    • Class 07: Review 2
    • Class 08: Final Exam 1
    • Class 09: Final Exam 2
    • Review "CTDL và Giải thuật với Java"
  • CTDL và Giải thuật với Java
    • Class 01: Hello Data Structure
  • HTML
    • Cài đặt công cụ cơ bản
    • HTML là gì?
    • Phần tử HTML
    • Cấu trúc file HTML cơ bản
    • Comment trong HTML
    • Format văn bản trong HTML
    • Thuộc tính HTML
    • Liên kết(link) trong HTML
    • Project: Professional Email
    • HTML Style
    • Phần tử Inline và Block
    • HTML Image
    • HTML List
    • HTML Table
    • Head trong HTML
    • HTML Responsive
    • Project: Online Cover Letter
  • CSS
    • Giới thiệu CSS
    • CSS Selector
    • Thêm CSS vào trang
    • Comment trong CSS
    • Màu sắc trong CSS
    • CSS Background
    • CSS Border
    • CSS Spacing
    • CSS Flexbox
    • HTML Layout
    • Chrome dev tools
    • CSS Box Model
    • CSS Position
    • Đơn vị đo trong CSS
    • CSS Pseudo-classes
    • CSS Responsive
  • JavaScript
    • Giới thiệu Javascript
    • Thêm JS vào trang
    • Các hàm có sẵn
    • Biến và kiểu dữ liệu
    • JS Mảng
    • JS Đối tượng
    • JS Biến Tham Chiếu và Tham Trị
    • Toán tử và biểu thức
    • Câu lệnh điều kiện
    • Vòng lặp For / While
    • Hàm (Function)
    • Chức năng tìm kiếm với JS và DOM
    • JS Class
    • JS DOM
    • JS Dom Rendering
  • Java
    • Giới thiệu Java
    • Chương trình Hello world
    • Phân biệt JVM, JRE, JDK
    • Java Comment
    • Biến trong Java
    • Kiểu dữ liệu trong Java
    • Java Array
    • Toán tử trong Java
    • Biễu thức trong Java
    • Java If-else
    • Java Switch
    • Vòng lặp For trong Java
    • Vòng lặp While trong Java
    • Vòng lặp Do-while trong Java
    • Java Method
    • Java OOP
    • Java Class và Object
    • Java Class attribute
    • Java Class method
    • Java Constructor
    • Java Modifier
    • Java Package
    • Java Tính kế thừa
    • Java Tính đa hình
    • Java Tính trừu tượng
    • Java Tính đóng gói
    • Java User Input
    • Java File
  • Soft skills
    • Pair Programming
  • Web design and wireframe
  • NextJS
    • Tạo dự án NextJS mới
  • NestJS
    • Giới thiệu NestJS
    • NestJS controller
    • NestJS module
  • Git
    • Setup SSH key với GitHub
  • Bash
    • Giới thiệu Bash/Shell Script
  • Wordpress
    • Thêm custom routes
    • Deploy with ubuntu
  • Deployment
    • SSH server, đổi password và add SSH key
    • Tạo user mới và add SSH key
    • Page
  • GitBook
    • Custom domain with CloudFlare
  • Hướng dẫn khác
    • Gitbook custom domain with Cloudflare
    • Cấu hình OpenVPN
    • Cấu hình và lấy SSH key
    • Công cụ lập trình
      • Visual Studio Code
      • Cài đặt IntelliJ IDEA
    • Đường dẫn file trong HTML
    • CI/CD github action
  • Project: CV online
Powered by GitBook
On this page
  • Java Class Method
  • Khai báo Method
  • Truyền tham số vào Method
  • Method trả về giá trị
  • Method Overloading
  • Bài tập thực hành
  1. Java

Java Class method

Java Class Method

Trong lập trình Java, method (phương thức) là các hàm hoặc thủ tục được định nghĩa bên trong một lớp và thực hiện các hành động hoặc thao tác trên đối tượng. Method có thể nhận tham số đầu vào và trả về kết quả đầu ra.

Khai báo Method

Method được khai báo bên trong một lớp. Cú pháp để khai báo một method như sau:

accessModifier returnType methodName(parameterList) {
    // body of method
}
  • accessModifier: Là từ khóa xác định quyền truy cập vào method, như public, private, hoặc protected.

  • returnType: Là kiểu dữ liệu của giá trị trả về từ method, nếu method không trả về giá trị thì sử dụng từ khóa void.

  • methodName: Là tên của method.

  • parameterList: Là danh sách các tham số mà method nhận vào (có thể rỗng).

Ví dụ:

public class Car {
    // Attribute
    private String color;
    private int maxSpeed;

    // Constructor
    public Car(String color, int maxSpeed) {
        this.color = color;
        this.maxSpeed = maxSpeed;
    }

    // Method để hiển thị thông tin của ô tô
    public void displayInfo() {
        System.out.println("Color: " + color);
        System.out.println("Max Speed: " + maxSpeed + " km/h");
    }
}

public class Main {
    public static void main(String[] args) {
        // Tạo một đối tượng ô tô từ lớp Car
        Car myCar = new Car("Red", 200);
        
        // Gọi phương thức hiển thị thông tin của ô tô
        myCar.displayInfo();
    }
}

Truyền tham số vào Method

Method có thể nhận các tham số đầu vào để thực hiện các thao tác khác nhau dựa trên giá trị của các tham số này. Tham số được khai báo trong danh sách tham số (parameter list) của method.

Ví dụ:

public class MathOperations {
    // Method để cộng hai số nguyên
    public int add(int a, int b) {
        return a + b;
    }

    // Method để trừ hai số nguyên
    public int subtract(int a, int b) {
        return a - b;
    }
}

public class Main {
    public static void main(String[] args) {
        MathOperations math = new MathOperations();
        
        // Gọi phương thức add
        int sum = math.add(5, 3);
        System.out.println("Sum: " + sum);
        
        // Gọi phương thức subtract
        int difference = math.subtract(5, 3);
        System.out.println("Difference: " + difference);
    }
}

Method trả về giá trị

Method có thể trả về một giá trị sau khi thực hiện các thao tác. Kiểu dữ liệu của giá trị trả về được khai báo trong phần returnType của method. Để trả về giá trị, sử dụng từ khóa return.

Ví dụ:

public class Circle {
    // Attribute
    private double radius;

    // Constructor
    public Circle(double radius) {
        this.radius = radius;
    }

    // Method để tính diện tích hình tròn
    public double calculateArea() {
        return Math.PI * radius * radius;
    }
}

public class Main {
    public static void main(String[] args) {
        Circle circle = new Circle(5.0);
        
        // Gọi phương thức calculateArea
        double area = circle.calculateArea();
        System.out.println("Area: " + area);
    }
}

Method Overloading

Method overloading là khả năng của một lớp để có nhiều method cùng tên nhưng khác nhau về danh sách tham số (số lượng tham số hoặc kiểu dữ liệu của tham số). Java hỗ trợ method overloading để tăng tính linh hoạt và tiện lợi khi gọi method.

Ví dụ:

public class MathOperations {
    // Method để cộng hai số nguyên
    public int add(int a, int b) {
        return a + b;
    }

    // Method để cộng ba số nguyên
    public int add(int a, int b, int c) {
        return a + b + c;
    }

    // Method để cộng hai số thực
    public double add(double a, double b) {
        return a + b;
    }
}

public class Main {
    public static void main(String[] args) {
        MathOperations math = new MathOperations();
        
        // Gọi các phương thức add khác nhau
        int sum1 = math.add(5, 3);
        int sum2 = math.add(5, 3, 2);
        double sum3 = math.add(5.5, 3.2);
        
        System.out.println("Sum1: " + sum1);
        System.out.println("Sum2: " + sum2);
        System.out.println("Sum3: " + sum3);
    }
}

Bài tập thực hành

Tạo lớp Calculator

  • Tạo một lớp Calculator với các phương thức add, subtract, multiply, và divide.

  • Các phương thức này nhận hai tham số đầu vào và trả về kết quả tương ứng.

Bài giải
public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }
    
    public int subtract(int a, int b) {
        return a - b;
    }
    
    public int multiply(int a, int b) {
        return a * b;
    }
    
    public double divide(int a, int b) {
        if (b != 0) {
            return (double) a / b;
        } else {
            throw new IllegalArgumentException("Division by zero is not allowed.");
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Calculator calc = new Calculator();
        
        int sum = calc.add(10, 5);
        int difference = calc.subtract(10, 5);
        int product = calc.multiply(10, 5);
        double quotient = calc.divide(10, 5);
        
        System.out.println("Sum: " + sum);
        System.out.println("Difference: " + difference);
        System.out.println("Product: " + product);
        System.out.println("Quotient: " + quotient);
    }
}

Method Overloading

  • Mở rộng lớp Calculator để hỗ trợ các phương thức add, subtract, multiply, và divide cho cả số nguyên và số thực.

Bài giải
public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }
    
    public double add(double a, double b) {
        return a + b;
    }
    
    public int subtract(int a, int b) {
        return a - b;
    }
    
    public double subtract(double a, double b) {
        return a - b;
    }
    
    public int multiply(int a, int b) {
        return a * b;
    }
    
    public double multiply(double a, double b) {
        return a * b;
    }
    
    public double divide(int a, int b) {
        if (b != 0) {
            return (double) a / b;
        } else {
            throw new IllegalArgumentException("Division by zero is not allowed.");
        }
    }
    
    public double divide(double a, double b) {
        if (b != 0.0) {
            return a / b;
        } else {
            throw new IllegalArgumentException("Division by zero is not allowed.");
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Calculator calc = new Calculator();
        
        int sumInt = calc.add(10, 5);
        double sumDouble = calc.add(10.5, 5.5);
        int differenceInt = calc.subtract(10, 5);
        double differenceDouble = calc.subtract(10.5, 5.5);
        int productInt = calc.multiply(10, 5);
        double productDouble = calc.multiply(10.5, 5.5);
        double quotientInt = calc.divide(10, 5);
        double quotientDouble = calc.divide(10.5, 5.5);
        
        System.out.println("Sum (int): " + sumInt);
        System.out.println("Sum (double): " + sumDouble);
        System.out.println("Difference (int): " + differenceInt);
        System.out.println("Difference (double): " + differenceDouble);
        System.out.println("Product (int): " + productInt);
        System.out.println("Product (double): " + productDouble);
        System.out.println("Quotient (int): " + quotientInt);
        System.out.println("Quotient (double): " + quotientDouble);
    }
}

Hãy thực hiện các bài tập để làm quen với việc sử dụng method trong Java.

PreviousJava Class attributeNextJava Constructor

Last updated 1 year ago