PORS是一种面向对象的编程语言,它支持多态、封装、继承和重用。多态:PORS支持多态,可以使用不同类型的数据作为参数,并返回相应的结果。例如:
PORS是一种面向对象的编程语言,它支持多态、封装、继承和重用。
1. 多态:PORS支持多态,可以使用不同类型的数据作为参数,并返回相应的结果。例如:
class Animal {
public void move() {
System.out.println("动物在移动");
}
}
class Dog extends Animal {
public void move() {
System.out.println("狗在奔跑");
}
}
public class TestPolymorphism {
public static void main(String[] args) {
Animal a = new Animal(); // Animal 对象
Animal b = new Dog(); // Dog 对象
a.move();// 执行 Animal 类的方法
b.move();//执行 Dog 类的方法
}
}
2. 封装:PORS支持封装,可以将类中的属性和方法隐藏起来,仅公开必要的接口,保护内部实现不被外界访问。例如:
public class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
3. 继承:PORS支持继承,子类可以继承父类的属性和方法,从而减少代码重复,提高代码复用性。例如:
class Animal {
public void move() {
System.out.println("动物在移动");
}
}
class Dog extends Animal {
public void bark() {
System.out.println("狗在叫");
}
}
4. 重用:PORS支持重用,可以创建多个对象,共享同一个类的属性和方法,大大减少了代码的编写量。例如:
class Animal {
public void move() {
System.out.println("动物在移动");
}
}
public class TestReuse {
public static void main(String[] args) {
Animal a1 = new Animal();
Animal a2 = new Animal();
Animal a3 = new Animal();
a1.move();
a2.move();
a3.move();
}
}
标签:
评论列表 (0)