一、基本概念
类(Class):它是创建对象的基础模板,封装了数据属性(变量)和行为(方法)。类描述了一组具有相似特性和行为的对象。
对象(Object):是类的实例,每个对象都有其特定的属性值,并能执行类中定义的方法。
有参构造
public Person(String name) {
this.name = name;}
无参构造 public Book() {}
二、特性
封装(Encapsulation):隐藏对象的内部细节,仅对外提供必要的接口访问。这有助于保持数据的安全性和控制复杂性。
public class Book {
//书名
private Stringname;
//价格
private double price;
//作者
private Stringauthor;
//类目
private Stringtype;
//无参构造
public Book() {}
/**
* \、Book累的有参构造
* @param name 书名
* @param price 价格
* @param author 作者
* @param type 类目
*/
public Book(String name,double price, String author, String type) {
this.name = name;
this.price = price;
this.author = author;
this.type = type;
}
public StringgetName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public StringgetAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public StringgetType() {
return type;
}
@Override
public StringtoString() {
return "Book{" +
"name='" +name +'\'' +
", price=" +price +
", author='" +author +'\'' +
", type='" +type +'\'' +
'}';
}
public void setType(String type) {
this.type = type;
}
}
继承(Inheritance):通过派生新类自现有类,新类继承原类的属性和方法,实现了代码复用和层次结构组织。
//父类 生物
public class Animal {
private Stringname;
public StringgetName() {
return name;
}
public Animal(String name,int age) {
this.name = name;
this.age = age;
}
@Override
public StringtoString() {
return "Animal{" +
"name='" +name +'\'' +
", age=" +age +
'}';
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
private int age;
public Animal(){}
}
----------------------------------------------------------------------------------------------------------------------------------------
public class Cat extends Animal{
private Stringtail;
public StringgetTail() {
return tail;
}
public void setTail(String tail) {
this.tail = tail;
}
@Override
public StringtoString() {
return "Cat{" +
"tail='" +tail +'\'' +
'}';
}
public Cat(String name,int age, String tail) {
super(name, age);
this.tail = tail;
}
public Cat(String tail) {
this.tail = tail;
}
public Cat(){}
}
--------------------
public class Maoextends Animal{
private boolean isEyes;
public boolean isEyes() {
return isEyes;
}
public void setEyes(boolean eyes) {
isEyes = eyes;
}
@Override
public StringtoString() {
return "Mao{" +
"isEyes=" +isEyes +
'}';
}
public Mao(String name,int age,boolean isEyes) {
super(name, age);
this.isEyes = isEyes;
}
public Mao() {
}
}
多态(Polymorphism):同一种行为在不同对象上表现出不同的效果,如前面提到的继承和接口重写等机制。
class Animal:
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):
return "汪汪汪"
class Cat(Animal):
def make_sound(self):
return "喵喵喵"
def animal_sound(animal):
print(animal.make_sound())
dog = Dog()
cat = Cat()
animal_sound(dog)
animal_sound(cat)
抽象类和接口(Abstract Class and Interface):抽象类允许部分实现,接口则只定义方法契约,主要用于规定行为规范。