Java 对象和类
作为一种典型的面向对象编程语言,Java 主要基于以下几个基本概念:
1. 类(Class)
- 定义:对象的模板,包含属性(字段)和方法
- 示例:public class Cat { ... }
2. 对象(Object)
- 定义:类的实例,拥有具体的状态(属性值)和行为(方法调用)
- 示例:Cat myCat = new Cat();
3. 方法(Method)
- 定义:定义类的行为,包含在类中的函数
- 示例:public void displayInfo() { System.out.println("Info"); }
4. 继承(Inheritance)
- 定义:子类继承父类的字段和方法,可扩展或重写。
- 示例:public class Cat extends Animal
public class Animal {
public void eat() { System.out.println("Eating..."); }
}
public class Cat extends Animal { // 继承
@Override
public void eat() { System.out.println("Cat eats bones"); } // 方法重写
}
5. 封装(Encapsulation)
- 定义:通过
private
字段+public
方法控制访问,隐藏内部细节。 - 示例:
public class BankAccount {
private double balance; // 私有字段
public void deposit(double amount) { // 公有方法
if (amount > 0) balance += amount;
}
}
6. 多态(Polymorphism)
- 定义:对象可以表现为多种形态,主要通过方法重载和方法重写实现。
- 方法重载(Overloading)示例:
class Printer {
// 打印整数
void print(int number) {
System.out.println("整数: " + number);
}
// 重载 - 打印字符串
void print(String text) {
System.out.println("字符串: " + text);
}
}
public class Main {
public static void main(String[] args) {
Printer p = new Printer();
p.print(100); // 调用print(int),输出结果:整数: 100
p.print("你好"); // 调用print(String),输出结果:字符串: 你好
}
}
- 方法重写(Overriding)示例:
class Animal {
void speak() {
System.out.println("动物发出声音");
}
}
class Dog extends Animal {
// 重写父类的speak方法
@Override
void speak() {
System.out.println("汪汪叫");
}
}
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.speak(); // 调用Dog类的speak方法,输出结果:汪汪叫
}
}
7. 抽象(Abstraction)
- 定义:通过抽象类或接口定义必须实现的方法,但不提供具体实现细节。
- 抽象类(Abstract Class)示例:public abstract class Shape { abstract void draw(); }
// 抽象类
public abstract class Shape {
// 抽象方法(必须由子类实现)
public abstract double calculateArea();
// 具体方法(可以直接继承)
public void display() {
System.out.println("This is a shape.");
}
}
// 子类实现抽象方法
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}
// 使用示例
public class Main {
public static void main(String[] args) {
Circle circle = new Circle(5.0);
System.out.println("Area: " + circle.calculateArea()); // 输出 78.53981633974483
circle.display(); // 输出 "This is a shape."
}
}
- 接口(Interface)示例:public interface Drawable { void draw(); }
// 接口
public interface Drawable {
// 抽象方法(必须由实现类实现)
void draw();
// 默认方法(可选实现)
default void printInfo() {
System.out.println("This is a drawable object.");
}
}
// 实现类
public class Rectangle implements Drawable {
@Override
public void draw() {
System.out.println("Drawing a rectangle...");
}
}
// 使用示例
public class Main {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle();
rectangle.draw(); // 输出 "Drawing a rectangle..."
rectangle.printInfo(); // 输出 "This is a drawable object."
}
}
评论区 0
发表评论
教程介绍
Java 通用高级编程语言,广泛应用在企业级应用开发、移动应用开发、大数据处理等领域。
12
章节
126
阅读
0
评论
反馈提交成功
感谢您的反馈,我们将尽快处理您的反馈