内容简介
系统讲解Java编程基础,涵盖Java语法基础、面向对象编程(封装、继承、多态)、异常处理、集合框架、输入输出等核心内容,配合编程实例。
Java程序设计入门教程——面向对象编程
概述
Java 是一门广泛使用的面向对象编程语言,由 Sun Microsystems(现 Oracle)的 James Gosling 于1995年推出。Java 的设计理念是"一次编写,到处运行"(Write Once, Run Anywhere),这得益于 Java 虚拟机(JVM)的跨平台特性。
Java 在企业级应用开发、Android 移动开发、大数据处理、Web 后端开发等领域有着广泛的应用。学习 Java 不仅是掌握一门编程语言,更是理解面向对象编程思想的过程。本教程将从 Java 基础语法出发,重点讲解面向对象编程的三大核心特性:封装、继承、多态,以及异常处理和集合框架等实用内容。
一、Java 基础语法
1.1 第一个 Java 程序
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
代码解析:
public class HelloWorld:定义一个名为 HelloWorld 的公共类,类名必须与文件名一致public static void main(String[] args):主方法,程序的入口点System.out.println():输出一行文本到控制台
1.2 数据类型
Java 的数据类型分为基本数据类型和引用数据类型。
基本数据类型(8种):
| 类型 | 大小 | 范围 | 示例 |
|---|---|---|---|
| byte | 1字节 | -128~127 | byte b = 100; |
| short | 2字节 | -32768~32767 | short s = 1000; |
| int | 4字节 | -2³¹~2³¹-1 | int i = 100000; |
| long | 8字节 | -2⁶³~2⁶³-1 | long l = 100000L; |
| float | 4字节 | ±3.4E38 | float f = 3.14f; |
| double | 8字节 | ±1.7E308 | double d = 3.14; |
| char | 2字节 | 0~65535 | char c = 'A'; |
| boolean | 1位 | true/false | boolean b = true; |
引用数据类型:类(class)、接口(interface)、数组(array)
1.3 控制结构
条件语句:
int score = 85;
if (score >= 90) {
System.out.println("优秀");
} else if (score >= 80) {
System.out.println("良好");
} else if (score >= 60) {
System.out.println("及格");
} else {
System.out.println("不及格");
}
循环语句:
// for循环:计算1到100的和
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
System.out.println("1到100的和为:" + sum);
// while循环
int count = 0;
while (count < 10) {
System.out.println("第" + (count + 1) + "次循环");
count++;
}
// 增强for循环(遍历数组)
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.println(num);
}
1.4 数组
// 声明和初始化
int[] arr = new int[5]; // 创建长度为5的数组
arr[0] = 10;
arr[1] = 20;
// 直接初始化
int[] arr2 = {1, 2, 3, 4, 5};
// 获取数组长度
System.out.println(arr2.length); // 输出5
// 遍历数组
for (int i = 0; i < arr2.length; i++) {
System.out.println("arr2[" + i + "] = " + arr2[i]);
}
二、面向对象编程——封装
2.1 类与对象
类是对象的模板或蓝图,对象是类的实例。
public class Student {
// 属性(成员变量)
private String name;
private int age;
private double gpa;
// 构造方法
public Student(String name, int age, double gpa) {
this.name = name;
this.age = age;
this.gpa = gpa;
}
// 方法(成员方法)
public void study(String subject) {
System.out.println(name + "正在学习" + subject);
}
// getter和setter方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age > 0 && age < 150) {
this.age = age;
} else {
System.out.println("年龄不合法!");
}
}
}
创建和使用对象:
Student stu = new Student("张三", 20, 3.8);
stu.study("Java编程");
System.out.println(stu.getName()); // 输出:张三
stu.setAge(21);
2.2 封装的意义
封装是将数据(属性)和操作数据的方法捆绑在一起,并通过访问修饰符控制外部对数据的直接访问。
Java 的访问修饰符:
| 修饰符 | 同类 | 同包 | 子类 | 其他包 |
|---|---|---|---|---|
| private | ✓ | ✗ | ✗ | ✗ |
| default | ✓ | ✓ | ✗ | ✗ |
| protected | ✓ | ✓ | ✓ | ✗ |
| public | ✓ | ✓ | ✓ | ✓ |
封装的好处:
- 隐藏实现细节,只暴露必要的接口
- 通过 getter/setter 方法控制数据的访问和修改
- 提高代码的安全性和可维护性
2.3 构造方法
构造方法是创建对象时自动调用的方法,用于初始化对象的属性。
public class Rectangle {
private double width;
private double height;
// 无参构造方法
public Rectangle() {
this.width = 1.0;
this.height = 1.0;
}
// 有参构造方法
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
// 计算面积
public double getArea() {
return width * height;
}
// 计算周长
public double getPerimeter() {
return 2 * (width + height);
}
}
三、面向对象编程——继承
3.1 继承的概念
继承是面向对象编程的重要特性,允许子类继承父类的属性和方法,实现代码复用。
// 父类
public class Animal {
protected String name;
protected int age;
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
public void eat() {
System.out.println(name + "在吃东西");
}
public void sleep() {
System.out.println(name + "在睡觉");
}
}
// 子类
public class Dog extends Animal {
private String breed;
public Dog(String name, int age, String breed) {
super(name, age); // 调用父类构造方法
this.breed = breed;
}
// 子类特有方法
public void bark() {
System.out.println(name + "在汪汪叫");
}
// 重写父类方法
@Override
public void eat() {
System.out.println(name + "在吃狗粮");
}
}
使用:
Dog dog = new Dog("旺财", 3, "金毛");
dog.eat(); // 输出:旺财在吃狗粮(调用重写后的方法)
dog.sleep(); // 输出:旺财在睡觉(继承自父类)
dog.bark(); // 输出:旺财在汪汪叫(子类特有方法)
3.2 方法重写(Override)
子类可以重写父类的方法,以实现不同的行为。重写的规则:
- 方法名、参数列表必须与父类相同
- 返回类型可以是父类返回类型的子类(协变返回类型)
- 访问权限不能比父类更严格
- 使用
@Override注解可以检查重写是否正确
3.3 super 关键字
super 用于引用父类的对象:
super():调用父类的构造方法,必须放在子类构造方法的第一行super.方法名():调用父类的方法super.属性名:访问父类的属性
3.4 Object 类
所有 Java 类都直接或间接继承自 Object 类。Object 类提供了以下常用方法:
toString():返回对象的字符串表示equals(Object obj):比较两个对象是否相等hashCode():返回对象的哈希码getClass():返回对象的运行时类
四、面向对象编程——多态
4.1 多态的概念
多态是指同一个方法调用可以根据对象的不同类型产生不同的行为。多态是面向对象编程最强大的特性之一。
public class Animal {
public void makeSound() {
System.out.println("动物发出声音");
}
}
public class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("喵喵喵");
}
}
public class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("汪汪汪");
}
}
public class Bird extends Animal {
@Override
public void makeSound() {
System.out.println("叽叽喳喳");
}
}
多态的使用:
// 父类引用指向子类对象
Animal animal1 = new Cat();
Animal animal2 = new Dog();
Animal animal3 = new Bird();
animal1.makeSound(); // 输出:喵喵喵
animal2.makeSound(); // 输出:汪汪汪
animal3.makeSound(); // 输出:叽叽喳喳
4.2 向上转型与向下转型
向上转型(自动):子类对象赋值给父类引用,是安全的。
Animal animal = new Cat(); // 向上转型
向下转型(强制):父类引用转换为子类类型,需要使用强制转换符,且必须确保对象的实际类型匹配。
Animal animal = new Cat();
Cat cat = (Cat) animal; // 向下转型,安全
// Dog dog = (Dog) animal; // 运行时错误!ClassCastException
instanceof 运算符:用于判断对象的实际类型。
if (animal instanceof Cat) {
Cat cat = (Cat) animal;
cat.makeSound();
}
4.3 多态的实际应用
多态最常见的应用场景是方法的参数类型使用父类类型:
public class AnimalShelter {
// 方法参数使用父类类型,可以接受任何子类对象
public void feedAnimal(Animal animal) {
System.out.print("喂养:");
animal.makeSound(); // 根据实际对象类型调用不同的方法
}
public static void main(String[] args) {
AnimalShelter shelter = new AnimalShelter();
shelter.feedAnimal(new Cat()); // 喂养:喵喵喵
shelter.feedAnimal(new Dog()); // 喂养:汪汪汪
shelter.feedAnimal(new Bird()); // 喂养:叽叽喳喳
}
}
五、异常处理
5.1 异常的概念
异常是程序运行时出现的错误或意外情况。Java 使用 try-catch-finally 机制来处理异常。
5.2 异常处理语法
try {
// 可能抛出异常的代码
int result = 10 / 0; // ArithmeticException
} catch (ArithmeticException e) {
// 处理特定类型的异常
System.out.println("算术异常:" + e.getMessage());
} catch (Exception e) {
// 处理其他类型的异常
System.out.println("发生异常:" + e.getMessage());
} finally {
// 无论是否发生异常都会执行
System.out.println("finally块执行");
}
5.3 异常的分类
Throwable
├── Error(错误,不可恢复)
│ ├── OutOfMemoryError
│ └── StackOverflowError
└── Exception(异常)
├── RuntimeException(运行时异常,可不处理)
│ ├── NullPointerException
│ ├── ArrayIndexOutOfBoundsException
│ ├── ClassCastException
│ └── ArithmeticException
└── 检查异常(必须处理)
├── IOException
├── SQLException
└── FileNotFoundException
5.4 自定义异常
public class InsufficientBalanceException extends Exception {
private double deficit;
public InsufficientBalanceException(double deficit) {
super("余额不足,缺少:" + deficit + "元");
this.deficit = deficit;
}
public double getDeficit() {
return deficit;
}
}
// 使用自定义异常
public class BankAccount {
private double balance;
public void withdraw(double amount) throws InsufficientBalanceException {
if (amount > balance) {
throw new InsufficientBalanceException(amount - balance);
}
balance -= amount;
}
}
六、集合框架
6.1 集合框架概述
Java 集合框架提供了一组用于存储和操作对象集合的类和接口。主要接口包括:
Collection
├── List(有序、可重复)
│ ├── ArrayList
│ ├── LinkedList
│ └── Vector
├── Set(无序、不可重复)
│ ├── HashSet
│ ├── LinkedHashSet
│ └── TreeSet
└── Queue(队列)
├── LinkedList
└── PriorityQueue
Map(键值对)
├── HashMap
├── LinkedHashMap
├── TreeMap
└── Hashtable
6.2 ArrayList
import java.util.ArrayList;
ArrayList<String> list = new ArrayList<>();
// 添加元素
list.add("苹果");
list.add("香蕉");
list.add("橘子");
// 获取元素
String fruit = list.get(0); // "苹果"
// 获取大小
int size = list.size(); // 3
// 遍历
for (String item : list) {
System.out.println(item);
}
// 删除元素
list.remove("香蕉"); // 按元素删除
list.remove(0); // 按索引删除
// 判断是否包含
boolean hasApple = list.contains("苹果"); // true
6.3 HashMap
import java.util.HashMap;
import java.util.Map;
HashMap<String, Integer> scores = new HashMap<>();
// 添加键值对
scores.put("张三", 95);
scores.put("李四", 88);
scores.put("王五", 92);
// 获取值
int zhangsanScore = scores.get("张三"); // 95
// 判断是否包含键
boolean hasKey = scores.containsKey("李四"); // true
// 遍历
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
// 获取大小
int size = scores.size(); // 3
// 删除
scores.remove("王五");
6.4 泛型
泛型允许在定义类、接口和方法时使用类型参数,提高代码的类型安全性和复用性。
// 泛型类
public class Box<T> {
private T content;
public void set(T content) {
this.content = content;
}
public T get() {
return content;
}
}
// 使用泛型
Box<String> stringBox = new Box<>();
stringBox.set("Hello");
String value = stringBox.get(); // 无需强制类型转换
Box<Integer> intBox = new Box<>();
intBox.set(42);
int number = intBox.get();
练习题
题目一
定义一个 Circle 类,包含半径属性、计算面积和周长的方法,以及适当的构造方法和 getter/setter。
答案:
public class Circle {
private double radius;
public Circle() {
this.radius = 1.0;
}
public Circle(double radius) {
if (radius > 0) {
this.radius = radius;
} else {
throw new IllegalArgumentException("半径必须大于0");
}
}
public double getArea() {
return Math.PI * radius * radius;
}
public double getCircumference() {
return 2 * Math.PI * radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
if (radius > 0) {
this.radius = radius;
}
}
}
题目二
解释以下代码的输出结果:
class A {
public void show() {
System.out.println("A.show");
}
}
class B extends A {
@Override
public void show() {
System.out.println("B.show");
}
}
class C extends A {
@Override
public void show() {
System.out.println("C.show");
}
}
A a = new B();
a.show();
a = new C();
a.show();
答案:输出为:
B.show
C.show
这是多态的体现。虽然变量 a 的类型是 A,但实际指向的对象类型不同,调用的 show() 方法也不同。第一次 a 指向 B 的实例,调用 B 的 show();第二次 a 指向 C 的实例,调用 C 的 show()。
题目三
编写一个方法,使用 ArrayList 存储5个学生的成绩,然后计算平均分、最高分和最低分。
答案:
import java.util.ArrayList;
import java.util.Collections;
public static void analyzeScores(ArrayList<Integer> scores) {
if (scores.isEmpty()) {
System.out.println("没有成绩数据");
return;
}
int sum = 0;
for (int score : scores) {
sum += score;
}
double average = (double) sum / scores.size();
int max = Collections.max(scores);
int min = Collections.min(scores);
System.out.println("平均分:" + average);
System.out.println("最高分:" + max);
System.out.println("最低分:" + min);
}
题目四
解释 try-catch-finally 中 finally 块的作用。如果 try 块中有 return 语句,finally 块还会执行吗?
答案:finally 块用于定义"无论是否发生异常都必须执行"的代码,通常用于释放资源(如关闭文件、数据库连接等)。即使 try 块中有 return 语句,finally 块仍然会执行。finally 块在 return 语句之前执行,但如果 finally 块中也有 return 语句,它会覆盖 try 块中的 return。
题目五
使用 HashMap 实现一个简单的英汉词典,支持添加单词、查询翻译和删除单词。
答案:
import java.util.HashMap;
public class Dictionary {
private HashMap<String, String> dict = new HashMap<>();
public void addWord(String english, String chinese) {
dict.put(english, chinese);
System.out.println("已添加:" + english + " -> " + chinese);
}
public String lookup(String english) {
if (dict.containsKey(english)) {
return dict.get(english);
} else {
return "未找到该单词";
}
}
public boolean removeWord(String english) {
if (dict.containsKey(english)) {
dict.remove(english);
return true;
}
return false;
}
public void showAll() {
for (String word : dict.keySet()) {
System.out.println(word + " -> " + dict.get(word));
}
}
}
总结
Java 面向对象编程的核心内容可以归纳为:
- 基础语法:数据类型、控制结构、数组——这些是编程的基础工具。
- 封装:通过类和对象将数据和方法捆绑,通过访问修饰符控制访问权限。
- 继承:子类继承父类的属性和方法,实现代码复用。方法重写让子类可以定制自己的行为。
- 多态:同一个方法调用根据对象类型产生不同行为,是面向对象最强大的特性。
- 异常处理:try-catch-finally 机制保证程序的健壮性。
- 集合框架:ArrayList、HashMap 等集合类是日常开发中最常用的工具。
学习 Java 编程最重要的是多写代码。光看不练是学不会编程的。建议每学完一个知识点,就动手写一个小项目来练习。比如学完类和对象,可以写一个"学生管理系统";学完集合框架,可以写一个"通讯录程序"。通过实践,你会真正理解面向对象编程的精髓。
文章声明
本文仅供学习和参考,不构成任何投资建议。如有侵权,请联系删除。