类
类里面包含变量和函数,对象是类的实例
源文件:
一个源文件中只能有一个public类。
一个源文件可以有多个非public类。
源文件的名称应该和public类的类名保持一致
每个源文件中,先写package语句,再写import语句,最后定义类。
package : package com.company;//package写入该文件的存储路径
类定义:
public: 所有对象均可以访问
private: 只有本类内部可以访问
protected:同一个包或者子类中可以访问
不添加修饰符:在同一个包中可以访问
前两种修饰比较常用
例子:
`
package xxx.xxx
class Student{
public int x;
private int y;
//x可以被所有对象访问
//y只能在class Student内部访问
不加修饰符在同一个package内部都能使用
}
`
静态(带static修饰符)成员变量/函数与普通成员变量/函数的区别:
所有static成员变量/函数在类中只有一份,被所有类的对象共享;
所有普通成员变量/函数在类的每个对象中都有独立的一份;
静态函数中只能调用静态函数/变量;普通函数中既可以调用普通函数/变量,也可以调用静态函数/变量。
静态变量的存储空间是共享的(自己理解,不一定对).访问静态变量最好用类名访问
类定义实例
`
class Point {
private int x;
private int y;
//构造函数
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public String toString() {
return String.format("(%d, %d)", x, y);
}
}
`
类的继承
每个类只能继承一个类
`
//ColorPoint extends Point ColorPoint类继承Point类
class ColorPoint extends Point{
private String color;
public ColorPoint(int x, int y, String color) {
super(x, y);//调用父类构造函数
this.color = color;
}
public void setColor(String color) {
this.color = color;
}
public String toString() {
return String.format("(%d, %d, %s)", super.getX(), super.getY(), this.color);
//super.getX(); 调用父类的getx()函数
}
}
//如果子类和父类有一个同名函数,优先调用子类的函数
//子类对象可以赋给父类 Point p = new ColorPoint();
//上诉称为多态,同一个类的实例,调用相同的函数,运行结果不同
`
接口
interface与class类似。主要用来定义类中所需包含的函数。
接口也可以继承其他接口,一个类可以实现多个接口。
接口的定义
接口中不添加修饰符时,默认为public。
`
package com.text.role;
public interface Role {
public void greet();
public void move();
public int getSpeed();
}
`
接口继承
和类的继承一样,但每个接口可以继承多个接口
package com.text.role;
public interface Hero extends Role {
public void attack();
}
接口的实现
每个类可以实现多个接口
`
package com.text.role.imple;
import com.text.role.Hero;
//要导入Hero包
//实现所有接口操作
//public class Zeus implements Hero, Role 继承多个接口
public class Zeus implements Hero {
public void attack() {
System.out.printf(“attack\n”);
}
public void greet() {
System.out.printf("Hi\n");
}
public void move() {
System.out.printf("move\n");
}
public int getSpeed() {
return 10;
}
}
`
接口的多态
不同类使用同样的接口输出不同
`package com.text;//类似该文件的存储路径
import com.text.Point;
import com.text.role.Hero;
import com.text.role.imple.Athena;
import com.text.role.imple.Zeus;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Zeus zeus = new Zeus();
// zeus.greet();
//Hero 类型的变量数组
Hero[] heros = {
new Zeus(), new Athena(),
};
for(Hero hero : heros)
{
hero.greet();//接口多态
}
}
}
`