Skip to content

Thinking Java

整理了一些 Java 关键字的意思,利于更好地理解 Java 程序

method, class, package

import java.util.Scanner;
public class Echo {
    public static void main(String[] args) {
        String line;
        Scanner in = new Scanner(System.in);

        System.out.print("Type something: ");
        line = in.nextLine();
        System.out.println("You said: " + line);
    }
}

转载自 Understanding Java Classes, Objects, and Methods

Classes

A class in Java is fundamentally a blueprint for creating objects. It encapsulates the structure and behavior that the objects instantiated from the class will have. A class is composed of two main components: fields and methods. Fields, also known as attributes or variables, hold the data or state of the object. Methods, on the other hand, are functions that define what the object can do.

A class can have various types of fields and methods, including constructors which are special methods used to initialize new objects.

Access modifiers such as private, public, and protected dictate how the fields and methods can be accessed, thus implementing encapsulation – one of the core principles of object-oriented programming.

A simple class:

public class Dog {
    // Fields (attributes)
    private String name;
    private int age;

    // Default Constructor
    public Dog() {
        // Initialize default values
        this.name = "Unknown";
        this.age = 0;
    }

    // Parameterized Constructor
    public Dog(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Additional methods can be added to enhance functionality
    public void displayInfo() {
        System.out.println(name + " is " + age + " years old.");
    }
}

Objects

An object is an instance of a class, and it encapsulates the state and behavior defined by the class blueprint.

Objects are created from a class using the new keyword followed by a call to a constructor of the class. Each object has its own copy of the class’s instance variables and can have distinct values for these fields, but the methods are shared among all instances of the class unless they are instance-specific (non-static methods).

creating an object from the Dog class:

Dog myDog = new Dog("Max", 3);
Dog anotherDog = new Dog();     // Uses default constructor

the same to the Scanner class:

Scanner in = new Scanner(System.in);        // 'in' is an object
xxx = in.nextInt();     // use '.' to use method

Methods

Methods in Java are blocks of code that perform a specific task. They can manipulate the object’s state, perform calculations, or execute any actions that are necessary for the object.

不看public的话,method很像函数

Expanding on the Dog class with more complex methods:

public class Dog {
    private String name;
    private int age;

    public Dog(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void bark() {
        System.out.println(name + " is barking!");
    }

    public void updateName(String newName) {
        name = newName;
        System.out.println("New name updated to: " + name);
    }

    public int getAge() {
        return age;
    }

    // A method to simulate aging
    public void birthday() {
        age++;
        System.out.println(name + " is now " + age + " years old.");
    }
}
1
2
3
4
5
6
7
8
9
public class Main {
    public static void main(String[] args) {
        Dog myDog = new Dog("Max", 3);
        myDog.bark(); // Output: Max is barking!
        myDog.birthday(); // Increases age by 1
        System.out.println("Max is now " + myDog.getAge() + " years old."); 
        // Output: Max is now 4 years old.
    }
}

Objects encapsulate data and provide methods to access and modify the data directly. Object-oriented programming makes it possible to hide messy details so that you can more easily use and understand code that other people wrote.

Class and Object

  • Defining a class creates a new object type with the same name.
  • Every object belongs to some object type; that is, it is an instance of some class.
  • A class definition is like a template for objects: it specifies what attributes the objects have and what methods can operate on them.
  • The new operator instantiates objects, that is, it creates new instances of a class.
  • Think of a class like a blueprint for a house: you can use the same blueprint to build any number of houses.
  • The methods that operate on an object type are defined in the class for that object.

Java 程序

class的定义

1
2
3
public class NameOfClass {
    //...
}

method的定义

static method:

  • 有static关键字
1
2
3
public static void newLine() {
    //...
}
  • 和C中的函数定义很相似

  • static method不能用 this

instance method:

  • 没有 static 关键字
1
2
3
4
5
public boolean equals(Time that) {
    return this.hour == that.hour
            && this.minute == that.minute
            && this.second == that.second;
}
  • 当我们引用instance method的时候,我们使用在类中的一个instance上(也就是对象上),例如: boolean ans = time1.equals(time3)

method的使用

static method

使用同一个class内的method的方式与C中函数调用的方式相同

public vs private vs protected

public 意味着method可以被其他class引用

private int hour 说明 hour 只能在本 class 内被访问

protected 意味着只能在本class及子class被访问

"指针''

创建数组时的数组名是指针

new 返回指针

static 关键字

static 变量:

  • 所有对象访问attribute都是相同的,只开辟了一个空间
  • class定义好了就存在

non-static:

  • 依附于instance,必须有实例才能使用

  • You can't call something that doesn't exist. Since you haven't created an object, the non-static method doesn't exist yet. A static method (by definition) always exists. from Brian Knoblauch


转载自 Static Variables in Java – Why and How to Use Static Methods

static variable:

Whenever a variable is declared as static, this means there is only one copy of it for the entire class, rather than each instance having its own copy. A static method means it can be called without creating an instance of the class.

1
2
3
4
5
6
7
public class StaticKeywordExample {
  private static int count = 0; // static variable  

  public static void printCount() { // static method
    System.out.println("Number of Example objects created so far: " + count);
  }
}

When a variable is declared static in Java programming, it means that the variable belongs to the class itself rather than to any specific instance of the class. This means that there is only one copy of the variable in memory, regardless of how many instances of the class are created.

static methods:

Static methods are methods that belong to the class rather than to any specific instance of the class. Static methods can be called directly on the class itself without needing to create an instance of the class first.

1
2
3
4
5
6
7
8
9
public class Calculation{
    public static int add(int a, int b) {
        return a + b;
    }

    public static int multiply(int a, int b) {
        return a * b;
    }
}

invoke:

int result = Calculation.add(5, 10);
System.out.println(result); // Output: 15

静态方法不能访问非静态变量和调用非静态方法

this 关键字

转载自 Medium | Java this Keyword

this keyword is used to refer to the current object inside a method or a constructor

this通常在以下情况使用:

  • when instance variables and parameters have the same name (if the name of the parameter and instance variable is different, the compiler automatically appends this keyword) , eg.
this.age = age;
  • this with Getters and Setters, to assign value inside the setter method, to access value inside the getter method

  • use this in constructor overloading

class Complex {

    private int a, b;

    // constructor with 2 parameters
    private Complex( int i, int j ){
        this.a = i;
        this.b = j;
    }

    // constructor with single parameter
    private Complex(int i){
        // invokes the constructor with 2 parameters
        this(i, i); 
    }

    // constructor with no parameter
    private Complex(){
        // invokes the constructor with single parameter
        this(0);
    }
}

Java 程序的运行

每个类 ( .java 文件) 做自己的事情

程序的入口是 public static void main(String[] args) (OOpre要求这个方法能且仅能出现在一个class中) (Q: 那其他情况难道可以有多个入口?)

一个class内直接引用函数,引用其他class的method要 .<method>

Arrays是一个class,有 Arrays.toString(<array variable>) ,也有 a.length