面向对象程序设计将程序看做是一系列对象组成,而不是一系列动作组成。
对象(实例):一个包含状态(数据)和行为(方法)的编程实体,是具体的。
类:具有相同特征的事物的抽象描述,是抽象的。
一个类里可以有多个对象
格式:访问修饰符 数据类型 属性名
例: public String name;
private int score;
格式:public 方法名(参数类型 参数名, ,){
}
public void printSum ( int n, int m){
int sum = n + m;
System.out.println("sum = " + sum);
}
类的定义示例代码:
public class Student {
//成员变量
private String name;
private int age;
//成员方法
public void study() {
this.age = 18;
this.name = "Peter";
System.out.println("student name is " + s.name);
System.out.println("student age is " + s.age);
}
格式:
public 类名(){ 方法体... }
public 类名(参数类型 参数名, ,){ 方法体... }
public class Fruit {
private String name;
private String taste;
private String color;
//有参构造函数
public Fruit(String name, String taste, String color) {
this.name = name;
this.taste = taste;
this.color = color;
}
//无参构造函数
public Fruit() {
this("Fruit", "Red", "Blue");
}
方法重载: 同一个方法通过参数选择实现不同的功能
格式:
1.方法名相同;
2.参数列表不同:参数类型,个数,顺序不同;
注意:返回值类型和访问修饰符不同,其他相同时不算重载;
示例:
输出结果:
继承是类与类之间的一种关系
继承是对原来类(父类)功能的扩展,并创建新的类(子类)
public class 子类(派生类) extends 父类(基类,超类)
**其中extends是关键字**
下面是示例代码:
父类的定义 示例:
public class Fruit {
private String name;
private String taste;
private String color;
public void show(){
System.out.println("Fruit Name: " + name);
System.out.println("Fruit Taste: " + taste);
System.out.println("Fruit Color: " + color);
}
子类的定义 示例:
public class apple extends Fruit {
//apple是Fruit的子类,继承关键字是extends
public void print() {
System.out.println(getName()+" is picked.");
}
public void show() {
//保留父类原来的功能
super.show();
//新增功能
System.out.println("Apple is fruit");
}
}
当父类中的方法不能满足当前子类的需求时,需要重写方法;
重写格式:
若要保留父类原有的功能:调用父类方法
用super表示当前类的父类对象
public void show() {
super.show();
System.out.println("Apple is fruit");
}