Java的三大特性是封装、继承和多态。
-
封装:这是面向对象方法的重要原则,其核心思想是将对象的属性和操作(或服务)结合为一个独立的整体,并尽可能隐藏对象的内部实现细节。这样可以提供更好的安全性,减少耦合,使得类的内部结构可以自由修改。在Java中,访问修饰符如public、private和protected等被用来控制对象的访问权限。
-
继承:这是从已有的类中派生出新的类的一种方式,新的类能吸收已有类的数据属性和行为,并能扩展新的能力。继承的主要优点是代码复用,子类可以直接使用父类的属性和方法,减少了代码的冗余。
-
多态:多态是指允许一个接口使用多种实际类型的能力。这也就是说,一个方法可以有多种实现版本,即“一种定义,多种实现”。多态的主要优点是提高了程序的扩展性和后期的可维护性。
代码示例:
import java.util.Scanner;
public class MyGoods {
private String name;
private String peison;
private int num;
private double price;
private String small_pic;
public MyGoods() {
}
public MyGoods(String name, double price, String peison, int num) {
this.name = name;
this.peison = peison;
this.num = num;
this.price = price;
}
public void show() {
System.out.println(this.name);
System.out.println(this.num);
System.out.println(this.price);
System.out.println(this.peison);
Scanner scanner = new Scanner(System.in);
System.out.println("请输入购买商品的数量");
while (true) {
try {
this.num = scanner.nextInt();
break;
} catch (Exception e) {
System.out.println("需要重新输入商品数量,你输入的有问题,请输入整数");
}
}
System.out.println("*********************");
System.out.println("1------立即购买");
System.out.println("2-------加入购物车");
System.out.println("*********************");
System.out.println("请选择你的购买意向,输入序号");
try {
int no = scanner.nextInt();
switch (no) {
case 1:
this.buy();
break;
case 2:
this.addcar();
break;
}
} catch (Exception e) {
this.buy();
}
}
public void buy() {
System.out.println("你购买了这个商品");
this.make_order();
}
public void addcar() {
System.out.println("你已经把商品加入购物车");
}
protected void make_order() {
// 代码是由订单类做的,不是由Goods模块做的,它只能由Order的开发人员实现
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getPeison() {
return peison;
}
public void setPeison(String peison) {
this.peison = peison;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getSmall_pic() {
return small_pic;
}
public void setSmall_pic(String small_pic) {
this.small_pic = small_pic;
}
}