Java对象是由其状态和行为定义的。状态表示对象的属性,而行为表示对象的能力。这种封装性使得Java程序员更容易开发和维护大型应用程序,其使用面向对象的开发方法代替了传统的面向过程的方法。
一、对象的创建和使用
对象的创建过程非常简单,只需要使用关键字“new”即可创建对象。使用对象也十分直观,只需要使用对象名加上成员访问操作符(dot)即可访问其属性和方法。
public class Car {
private String brand; // 品牌
private String color; // 颜色
private int speed; // 速度
// 构造函数
public Car(String brand, String color) {
this.brand = brand;
this.color = color;
this.speed = 0;
}
// 获取品牌
public String getBrand() {
return brand;
}
// 获取颜色
public String getColor() {
return color;
}
// 获取速度
public int getSpeed() {
return speed;
}
// 加速
public void speedUp(int speed) {
this.speed += speed;
}
// 减速
public void slowDown(int speed) {
this.speed -= speed;
}
}
public class Main {
public static void main(String[] args) {
Car car1 = new Car("Toyota", "Red");
Car car2 = new Car("Honda", "Blue");
car1.speedUp(10);
System.out.println(car1.getBrand() + " " + car1.getColor() + " " + car1.getSpeed());
car2.speedUp(20);
System.out.println(car2.getBrand() + " " + car2.getColor() + " " + car2.getSpeed());
}
}
上述代码中,我们定义了一个Car类,其中包含了品牌、颜色和速度三个属性,以及加速和减速方法。我们使用这个类创建了两个不同的对象car1和car2,并分别使用speedUp方法将其速度增加10和20。
二、继承
继承是面向对象编程中的一种重要机制,允许创建一个类别,从已有类别继承属性和方法,并且在此基础上添加新的属性和方法。继承可以大幅减少代码量,同时也方便了程序员进行代码复用和修改。
// 父类Person
public class Person {
protected String name;
protected int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void sayHello() {
System.out.println("Hello, my name is " + name + ", I'm " + age + " years old.");
}
}
// 子类Student
public class Student extends Person {
protected String school;
public Student(String name, int age, String school) {
super(name, age);
this.school = school;
}
public void study() {
System.out.println("I'm studying at " + school + ".");
}
}
public class Main {
public static void main(String[] args) {
Student student = new Student("Alice", 18, "Beijing University");
student.sayHello();
student.study();
}
}
上述代码中,我们定义了一个Person类和一个Student类。Student类继承自Person类,继承了其属性和方法,并且在此基础上添加了一个school属性和一个study方法。
三、封装
封装是面向对象编程中的一个重要机制,原则是将类的实现细节隐藏在内部,只暴露必要的接口供外部使用。封装可以提高安全性、降低耦合和提高复用率。
public class Account {
private String name;
private double balance;
public void deposit(double amount) {
balance += amount;
}
public void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
} else {
System.out.println("Insufficient balance!");
}
}
public double getBalance() {
return balance;
}
}
public class Main {
public static void main(String[] args) {
Account account = new Account();
account.deposit(1000);
account.withdraw(500);
System.out.println(account.getBalance());
}
}
上述代码中,我们定义了一个Account类,其中包含了一个私有的balance属性和三个公有的方法deposit、withdraw和getBalance。我们使用deposit和withdraw方法来修改balance属性,而getBalance方法则用来获取balance属性。由于balance属性被定义成私有的,外部的程序无法直接访问balance属性,只能通过公有的方法来操作和获取其值。
原创文章,作者:GBOE,如若转载,请注明出处:https://www.506064.com/n/146175.html
微信扫一扫
支付宝扫一扫