Java基础

本文介绍了Java编程的基础,如类、对象、方法、继承、多态、异常处理、线程、包和接口,以及关键概念如静态成员、final与abstract。通过实例演示了语法、构造函数、访问修饰符、封装与抽象等核心知识点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. syntax

main() method

public class Main {
	public static void main(String[] args) {
		System.out.println("Hello");
	}
}
  1. Every line of code that runs in Java must be inside a class. In our example, we named the class Main. A class should always start with an uppercase first letter.
  2. Java is case-sensitive.
  3. The name of the java file must match the class name.
  4. The main() method is required and you will see it in every Java program.

casting

double d = 9.78d;
int i = (int) d;

2. method

The keyword static indicates that the particular member belongs to a type itself, rather than to an instance of that type.

example

public class Main {
	static void myMethod() {
		System.out.println("I just got executed!");
	}
}

static means that the method belongs to the Main class and not to an object of the Main class. It means that only one instance of that static member is created which is shared across all instances of the class.

method overloading

// With method overloading, multiple methods can have the same name with different parameters:
int myMethod(int x)
float myMethod(float x)
double myMethod(double x, double y)

3. class

An object is an instance of a class.

create a class

public class Main {
	int x = 5;
}

create an object

public class Main {
	int x = 5;
	public static void main(String[] args) {
		Main myObj = new Main();
		System.out.println(myObj.x);
	}
}

using multiple classes

You can also create an object of a class and access it in another class.
In this example, we have created two files in the same folder, Main.java and Second.java.

// Main.java
public class Main {
	int x = 5;
}
// Second.java
public class Second {
	public static void main(String[] args) {
		Main myObj = new Main();
		System.out.println(myObj.x);
	}
}

attributes

Class attributes are variables within a class. Another term for class attributes is fields.
If you don’t want the ability to override existing values, declare the attribute as final.

public class Main {
	final int x = 10;
}

The final, static, and public keywords are called “modifiers”.

methods

public class Main {
	static void myMethod() {
		System.out.println("Hello World!");
	}
	public static void main(String[] args) {
		myMethod(); // static method => can be accessed without creating an object of the class
	}
}

We created a static method, which means that it can be accessed without creating an object of the class, unlike public, which can only be accessed by objects:

public class Main {
	static void m1() {
		System.out.println("static");
	}
	public void m2() {
		System.out.println("public");
	}
	public static void main(String[] args) {
		m1();
		m2(); // error
		Main myObj = new Main();
		myObj.m2(); // no error
	}
}

The dot operator . is used to access the object’s attributes and methods.

constructors

A constructor is a special method. The constructor is called when an object of a class is created.

public class Main {
	int x;
	public Main(int y) {
		x = y;
	}
	public static void main(String[] args) {
		Main myObj = new Main(5);
		System.out.println(myObj.x);
	}
}

4. access modifiers

The public keyword is an access modifier, meaning that it is used to set the access level for classes, attributes, methods (include constructors).
For classes, you can use either public or default.

  • public: the class is accessible by other class
  • default: the class is only accessible by classes in the same package

For attributes, methods (include constructors), you can use:

  • public: the code is accessible for all classes
  • private: the code is only accessible within the declared class
  • default: the code is only accessible by classes in the same package
  • protected: the code is accessible in the same package and subclasses

5. non-access modifiers

For classes, you can use either final or abstract.

  • final: the class cannot be inherited by other classes
  • abstract: the class cannot be used to create objects

For attributes and methods (doesn’t include constructors), you can use:

  • final: attributes and methods cannot be overridden/modified
  • static: the attribute/method belongs to the class, rather than an object; only one instance of that static attribute/method is created which is shared across all instances of the class
  • abstract: can only be used in an abstract class, and can only be used on methods; the method does not have a body, for example, abstract void run(); the body is provided by the subclass; an abstract method belongs to an abstract class
  • transient: attributes and methods are skipped when serializing the object containing them; note that serialization is the process of converting an object into a byte stream
  • synchronized: methods can only be accessed by one thread at a time
  • volatile: the value of an attribute is not not cached thread-locally, and is always read from the main memory

6. encapsulation

Encapsulation: sensitive data is hidden from users.

  • declare class variables/attributes as private
  • provide public get and set methods to access and update the value of a private variable
public class Person {
	private String name;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}
  • read-only: only provide the get method
  • write-only: only provide the set method

7. packages

A package is used to group related classes. Think of it as a folder.
Packages are divided into two categories.

  • Built-in packages: packages from the Java API
  • User-defined packages

built-in packages

The Java API is a library of prewritten classes included in the JDE.
The library is divided into packages and classes: you can either import a single class, or a whole package that contain all the classes that belong to the specific package.

import java.util.Scanner; // import a single class
import java.util.*; // import a whole package

In our example, java.util is a package, while Scanner is a class.

user-defined packages

To create a package, use the package keyword.

package mypack;
class MyPackageClass {
	public static void main() {
		// your code...
	}
}

The package name should be written in lower case to avoid conflict with class names. Use javac -d [path] MyPackageClass.java to force the compiler to create the package.

8. inheritance

It is possible to inherit attributes and methods from one class to another.
To inherit from a class, use the extends keyword.

class Vehicle {
	protected String brand = "Ford";
	public void honk() {
		System.out.println("Tuut, tuut!");
	}
}
class Car extends Vehicle {
	private String modelName = "Mustang";
	public static void main(String[] args) {
		Car myCar = new Car();
		myCar.honk();
		System.out.println(myCar.brand + " " + myCar.modelName);
	}
}

If you don’t want other classes to inherit from a class, use the final keyword.

final class Vehicle {
	...
}

polymorphism

Polymorphism occurs when we have many classes that are related to each other by inheritance. Inheritance let us inherit attributes and methods from another class, while polymorphism uses thoes methods to perform different tasks.

Skipped Chapter: Java Inner Classes:
https://www.w3schools.com/java/java_inner_classes.asp

abstraction

abstract class Animal {
	public abstract void animalSound();
	public void sleep() {
		System.out.println("Zzz");
	}
}
class Pig extends Animal {
	public void animalSound() {
		System.out.println("The pig says: wee wee");
	}
}
class Main {
	Pig myPig = new Pig();
	myPig.animalSound();
	myPig.sleep();
}

abstraction by interfaces

An interface is a completely abstract class that is used to group related methods with empty bodies.

// interface
interface Animal {
	public void animalSound();
	public void run();
}

Use implements instead of extends.

interface Animal {
	public void animalSound();
	public void sleep();
}
class Pig implements Animal {
	public void animalSound() {
		System.out.println("The pig says: wee wee");
	}
	public void sleep() {
		System.out.println("Zzz");
	}
}
class Main {
	Pig myPig = new Pig();
	myPig.animalSound();
	myPig.sleep();
}
  1. Both interface and abstract class cannot be used to create objects.
  2. interface methods are by default abstract and public.
  3. interface attributes are by default public and static, and final.

why interface?

Java does not support “multiple inheritance” (a class can only inherit from one superclass). With interfaces, we can do that.
Multiple interfaces:

class DemoClass implements FirstInterface, SecondInterface {
	...
}

9. enumerate

// Java enum is a special "class"!
enum Level {
	LOW,
	MEDIUM,
	HIGH
}
// access enum
Level myVar = Level.MEDIUM;

Use enum inside a class:

public class Main {
	enum Level {
		LOW,
		MEDIUM,
		HIGH
	}
	public static void main(String[] args) {
		Level myVar = Level.MEDIUM;
		System.out.println(myVar);
	}
}

Loop through an enum:

for (Level myVar : Level.values()) {
	System.out.println(myVar);
}
  1. An enum can, just like a class, have attributes and methods. The only difference is that enum constants are public, static and final (unchangeable - cannot be overridden).
  2. An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).

Skipped chapters: user input, date, data structures, wrapper classes, regular expressions, lambda.
https://www.w3schools.com/java/java_user_input.asp
https://www.w3schools.com/java/java_date.asp
https://www.w3schools.com/java/java_arraylist.asp
https://www.w3schools.com/java/java_linkedlist.asp
https://www.w3schools.com/java/java_hashmap.asp
https://www.w3schools.com/java/java_hashset.asp
https://www.w3schools.com/java/java_iterator.asp
https://www.w3schools.com/java/java_wrapper_classes.asp
https://www.w3schools.com/java/java_regex.asp
https://www.w3schools.com/java/java_lambda.asp

10. exception: exceptional event

throw an exception object

当一个错误在一个method中发生时,这个method会创造出一个exception对象,并把这个对象交给runtime system来处理。这个exception对象中包含了错误的类型以及错误发生时程序的状态。创造一个exception对象并把这个对象交给runtime system处理的这个过程被称为throwing一个exception对象。在method将exception对象throw之后,runtime system将尝试处理这个exception对象。runtime system会按照method调用的时间顺序由近及远寻找可以处理这个exception对象的method(可以处理exception对象的method被称为exception handler),也就是,根据call stack的顺序由栈顶向栈底搜索exception handler。如果runtime system在寻找完所有的method后仍然没有找到handler,那么runtime system以及程序会终止运行。

catch or specify requirement

有几率throw某类型exception对象(不包括unchecked exception对象)的代码必须在以下两项中任选一项:(Catch or Specify规约)

  1. 一个try陈述
  2. 一个method来明确表示这个method可以throw这种类型的exception对象
    如果不满足以上的两项中的任何一项,代码将无法编译。

3 types of exception

exception分为三类。第一类是checked exception。这类exception可以被程序员事先考虑到。举例:java.io.FileNotFoundExceptionIOException。这类exception必须遵守Catch or Specify规约。所有的除了Error和RuntimeException的exception都属于这类。剩下的两类exception都不需要遵守Catch or Specify规约。
第二类是error。这类exception和应用内部无关,程序员也不能事先考虑到。举例:硬件故障或者系统故障,java.io.IOError。当JVM发生动态linking故障或者硬件故障时,JVM会“丢出”一个error类exception。简单的程序通常不会catch或者throw error。
第三类是runtime exception。这类exception出现在应用内部,应该被程序员避免。比如:程序bug,逻辑错误,或者是错误使用API,比如试图读取一个只有n个元素的数组的第n+1个元素。NullPointerExceptionIndexOutOfBoundsException。与其说程序员应该试图catch这类exception,不如说应该尝试避免发生这种exception in the first place。

exception handler

首先,将可能会throw exception的代码用一个try模块包裹起来。接下来,紧接着try模块,需要写1个或者多个catch模块。必须是紧接着,中间不能有其他代码。每一个catch模块需要传入一个exception类型参数。当try模块运行完成后,finally模块就会开始执行。finally模块的这种特性常被用于防止资源泄露,内存泄漏。

try-with-resources

任何一个implement java.io.AutoCloseable | java.io.Closeable的对象都可以被视为一个resource。如果try-with-resources和try模块同时创造了exception,那么按照先后顺序,try-with- resources的exception将会被suppressed,method会throw try模块的exception。如果是一个try模块和一个finally模块同时创造了exception,按照先后顺序,try模块throw的exception会被suppressed。twr的作用,和finally很相似,是确保在twr中声明的资源无论发生什么情况都可以正常关闭。

examples

public class Main {
	public static void main(String[] args) {
		try {
			int[] array = {1, 2};
			int[10] = 10;
		} catch(Exception e) {
			// print something here...
		} finally {
			// print something here...
			// code here will always be executed
		}
	}
}

The throw statement allows you to create a custom error.

11. threads

extending the Thread class and overriding its run() method

The thread can be run by creating an instance of the class and call its start() method.

public class Main extends Thread {
	public void run() {
		// do something here...
	}
	public static void main(String[] args) {
		Main thread = new Main();
		thread.start();
		// do some other thing here...
	}
}

implement the Runnable interface

The thread can be run by passing an instance of the class to a Thread object’s constructor and then calling the thread’s start() method.

public class Main implements Runnable {
	public void run() {
		// do something here...
	}
	public static void main(String[] args) {
		Main obj = new Main();
		Thread thread = new Thread(obj);
		thread.start();
		// do some other thing here...
	}
}

differences between the above-mentioned two methods

When a class extends the Thread class, you cannot extend any other class, but by implementing the Runnable interface, it is possible to extend from another class as well.

isAlive() and concurrency problem

while(thread.isAlive()) {
	System.out.println("Waiting...");
}

12. thread object

每一个线程都和一个Thread类的一个instance联系起来。用Thread对象有两种策略来设计并发程序。第一种策略是直接控制线程创建和管理:每次在程序需要initiate一个asynchronous任务时instantiate一个线程对象。第二种策略是abstract线程管理from the rest of your应用程序,pass应用程序的任务to一个executor。

defining and starting a thread

一个创建了一个Thread的instance的application必须提供在那个thread中将会运行的代码。有两种方法达到这个效果。而其中第一种方法更好。这种方法是:implements Runnable。提供一个Runnable对象。Runnable interface里定义了且只定义了一个方法,run,meant to contain在那个thread中将会运行的代码。我们需要把一个Runnable对象当作参数传入线程的构造函数中,如下:

public class ExampleRunnableClass implements Runnable {
	public void run() {
		// the code executed in the thread
	}
	public static void main(String args[]) {
		(new Thread(new ExampleRunnableClass())).start();
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值