OOP 的核心概念包括以下几个方面
类 对象 封装 继承 多态 抽象
类--抽象
对象--实际存在
继承:一个父类多个子类,一个子类只有一个父类可以继承父类的所有属性
多态:多态是面向对象编程中的一个重要概念,它允许对象在不同情况下表现出不同的行为。多态通常通过方法重写和父类引用指向子类对象来实现。
eg:
//父类
关键extends
public class Animal {
private Stringname;
private int age;
//有参构造
public Animal(String name,int age) {
this.name = name;
this.age = age;
}
//无参构造
public Animal() {
}
@Override
public StringtoString() {
return "Animal{" +
"name='" +name +'\'' +
", age=" +age +
'}';
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public StringgetName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
子类
public class Catextends Animal {
private Stringtall;
public Cat(String name,int age, String tall) {
super(name, age);
this.tall = tall;
}
public Cat() {
}
public Cat(String tall) {
this.tall = tall;
}
public StringgetTall() {
return tall;
}
public void setTall(String tall) {
this.tall = tall;
}
@Override
public StringtoString() {
return "Cat{" +
"tall='" +tall +'\'' +
'}';
}
}
public class Maoextends Animal {
public boolean isEyes;
public boolean isEyes() {
return isEyes;
}
public void setEyes(boolean eyes) {
isEyes = eyes;
}
public Mao(String name,int age,boolean isEyes) {
super(name ,age);
this.isEyes = isEyes;
}
public Mao(){
}
@Override
public StringtoString() {
return "Mao{" +
"isEyes=" +isEyes +
'}';
}
}
// System.out.println();
// System.out.println(book.toString());
// Mao bigMao = new Mao();
// bigMao.setName("大毛");
// bigMao.setAge(18);
// bigMao.setEyes(true);
// System.out.println(bigMao.toString());
// }
//使用多态
// Animal mao = new Mao();
// Animal cat = new Cat();
// System.out.println(bigMao.toString());
类
书
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;
}
public void setType(String type) {
this.type = type;
}
@Override
public StringtoString() {
return "Book{" +
"name='" +name +'\'' +
", price=" +price +
", author='" +author +'\'' +
", type='" +type +'\'' +
'}';
}
}
链接
public interface TestService {
/**
* 随便说点什么
* @param msg 要说的话
* @return 经过处理后的值
*/
StringsaySomething(String msg);
}
//实现类实现接口
public class TestServiceImplimplements TestService{
@Override
public StringsaySomething(String msg) {
return "ken 说:"+msg;
}
}
TestService testService =new TestServiceImpl();
System.out.println(testService.saySomething("123"));
构造函数 toString(),Getter和Setter函数可以直接生成