CS61B - Lecture 1

Lecture 1. Introduction

1. Basic Rules in Java

Java is an object oriented language with strict requirements:

  • Every Java file must contain a class declaration.
  • All code lives inside a class, even helper functions, global constants, etc.
  • To run a Java program, you typically define a main method using public static void main(String[] args).

Java is statically typed (not like Python):

  • All variables, parameters, and methods must have a declared type.That type can never change.
  • Expressions also have a type, e.g. “larger(5, 10) + 3” has type int.
  • The compiler checks that all the types in your program are compatible before the program ever runs! (This is unlike a language like Python, where type checks are performed DURING execution.)
    e.g. String x = larger(5, 10) + 3 will fail to compile.
  • Functions must be declared as part of a class in Java. A function that is part of a class is called a “method”.
  • All parameters of a function must have a declared type, and the return value of the function must have a declared type.
  • Functions in Java return only one value!

2. Compilation in Java

20241121164320

20241121164320

.class:

  • .class file has been type checked. Distributed code is safer.
  • .class files are ‘simpler’ for machine to execute. Distributed code is faster.
  • Minor benefit: Protects your intellectual property. No need to give out source.

3. Object-Oriented Programming

3.1 Class

  • A class serves as a template for all of its instances.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Car {
// 属性(成员变量)
String brand;
int speed;
// 构造方法(初始化对象时调用)
Car(String brand, int speed) {
this.brand = brand;
this.speed = speed;
}

// 行为(方法)
void drive() {
System.out.println(brand + " is driving at " + speed + " km/h");
}
}

3.2 Object

  • Each object is an instance of some class.
1
2
3
4
5
6
public class Main {
public static void main(String[] args) {
Car car1 = new Car("Toyota", 100); // 创建对象
car1.drive(); // 输出: Toyota is driving at 100 km/h
}
}

3.3 Encapsulation

  • Encapsulation is the practice of hiding an object’s internal state and exposing only selected methods for accessing or modifying it.

  • Benefits:
    1.Protects data from unauthorized access.
    2.Provides controlled interaction with data.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class BankAccount {
private double balance; // 私有变量,只有通过公开方法才可修改/查看

// 构造器
public BankAccount(double initialBalance) {
this.balance = initialBalance;
}

// 公开方法用于访问和修改私有变量
public double getBalance() {
return balance;
}

// 只能通过存钱来更改余额
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}

// 只能通过取钱来更改余额
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
}
}
}

3.4 Inheritance

  • Inheritance is a mechanism where a class (child) derives properties and behaviors from another class (parent).
  • Benefits:
    1.Promotes code reuse.
    2.Establishes a natural hierarchy.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Animal {
void eat() {
System.out.println("This animal eats food");
}
}

// Dog 是 Animal 的子类
class Dog extends Animal {
void bark() {
System.out.println("The dog barks");
}
}

public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // 从父类继承的方法
dog.bark(); // 子类的方法
}
}

3.5 Polymorphism

  • Polymorphism allows the same operation to behave differently on different classes.It is achieved through method overloading and method overriding.
3.5.1 method overloading

Same method name with different parameter lists.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Calculator {
int add(int a, int b) {
return a + b;
}

double add(double a, double b) {
return a + b;
}
}

public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(3, 4)); // 输出: 7
System.out.println(calc.add(3.5, 4.5)); // 输出: 8.0
}
}
3.5.2 method overriding

A subclass modifies the behavior of a method from its parent class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Animal {
void makeSound() {
System.out.println("Some generic animal sound");
}
}

class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Meow");
}
}

public class Main {
public static void main(String[] args) {
Animal animal = new Cat();
animal.makeSound(); // 输出: Meow
}
}

3.6 Abstraction

Abstraction focuses on exposing only essential features while hiding the implementation details. It is achieved through abstract classes or interfaces.

3.6.1 Abstract Class

Abstract Class cannot be instantiated, and it can only be inherited (extends).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// 抽象类定义了通用支付方法
abstract class Payment {
// 抽象方法只能被子类提供具体实现
abstract void processPayment(double amount);

// 具体方法被所有支付方式子类共享
void showPaymentInfo() {
System.out.println("Processing payment...");
}
}

// 子类1
class CreditCardPayment extends Payment {
@Override
void processPayment(double amount) {
System.out.println("Paid $" + amount + " using Credit Card.");
}
}

// 子类2
class PayPalPayment extends Payment {
@Override
void processPayment(double amount) {
System.out.println("Paid $" + amount + " using PayPal.");
}
}

public class Main {
public static void main(String[] args) {
// Use Payment through Polymorphism

// 1. Use CreditCardPayment
Payment payment1 = new CreditCardPayment();
payment1.showPaymentInfo();
payment1.processPayment(100.50); // 输出: Paid $100.5 using Credit Card.

// 2. Use PayPalPayment
Payment payment2 = new PayPalPayment();
payment2.showPaymentInfo();
payment2.processPayment(200.75); // 输出: Paid $200.75 using PayPal.
}
}
3.6.2 Interface
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// 接口中定义的方法没有具体实现,只是一个“规范”
interface Payment {
void processPayment(double amount);
}

// CreditCardPayment 类实现了 Payment 接口
class CreditCardPayment implements Payment {
@Override
public void processPayment(double amount) {
System.out.println("Paid $" + amount + " using Credit Card.");
}
}

// PayPalPayment 类实现了 Payment 接口
class PayPalPayment implements Payment {
@Override
public void processPayment(double amount) {
System.out.println("Paid $" + amount + " using PayPal.");
}
}

public class Main {
// 使用接口类型的变量来存储不同的支付方式对象
public static void main(String[] args) {
Payment payment1 = new CreditCardPayment();
payment1.processPayment(100.50); // 输出: Paid $100.50 using Credit Card.

Payment payment2 = new PayPalPayment();
payment2.processPayment(200.75); // 输出: Paid $200.75 using PayPal.
}
}
作者

Zylll

发布于

2024-11-21

更新于

2024-11-23

许可协议