static
static意为静态的,一般用来修饰变量和方法,被修饰的变量称为静态变量或类变量,被修饰的方法称为静态方法或类方法。
特点:
- 类变量和类方法被类的所有对象所共享
- 类变量和类方法可以被类名直接调用
- 类方法中只能调用类变量
public class Demo4 {
int a=10;
static int b=10;
public static void mathon(){
//a=20;//a没有被static修饰,是非静态变量,不能在静态方法中调用
System.out.println(b+1);
}
}
public class Test4 {
public static void main(String[] args) {
Demo4 d1=new Demo4();
Demo4 d2=new Demo4();
System.out.println(d1.b);//10
System.out.println(d2.b);//10
d1.b=20;
System.out.println(d1.b);//20
System.out.println(d2.b);//20,因为类变量被类的所有对象共享,所以d1修改b之后,使用d2打印b也是修改后的值
}
}
继承
继承是面向对象的三大特性之一,指子类继承父类,使用extends关键字,继承的方式是子类重写父类的方法。
重写:只有方法体不同,因此子类不能重写父类的构造方法,因为方法名不同。
创建子类对象后,子类对象可以调用父类的内容。
public class Father {
int a=10;
public void A(){
System.out.println("父类独有方法");
}
public void B(){
System.out.println("需要子类重写的方法");
}
}
public class Son extends Father{
public void B(){
System.out.println("子类重写父类方法");
}
}
public class Test {
public static void main(String[] args) {
Son s=new Son();
s.B();
s.A();//子类对象调用父类的方法
System.out.println(s.a);//子类对象调用父类的成员变量
}
}
子类重写父类方法
父类独有方法
10
Process finished with exit code 0
final
final关键字意为最终的,可以修饰类、变量、方法。
修饰类时,类不能被继承
修饰变量时,变量变为常量
修饰方法时,方法不能被重写
public final class Father{
}
public class Son extends Father{
}//报错,final修饰的类不能被继承
………………………………………………………………………………
public class Demo{
public static void main(String[] args){
final int a=10;
a=20;//会报错,变量a被final修饰变为常量,其值不能被修改
}
}
………………………………………………………………………………
public class A{
String s="天天向上";
public void mathon(){
System.out.println("好好学习");
}
}
public class Test{
public static void main(String[] args){
final A a=new A();
a.s="good study"//不会报错,final修饰的是a,存储对象的地址值,地址值不变,但对象的内容是可变的
}
}
多态
多态是面向对象的又一个特性,是指同一个事物有多种不同的表现形态。也是通过子类和父类体现出来的,例如:父类Animal有eat这个行为,对于不同的子类则有不同的表现形态,狗吃肉,猫吃鱼,羊吃草等。这个功能的实现方式有重写、接口、抽象类和抽象方法。
实现多态的前提:
- 类之间存在继承或实现关系
- 父类的变量接收子类的对象
- 方法的重写(非必须)
多态的使用:
- 在主函数中创建对象,例如:Father f=new Son();
- 调用的是父类的内容,调用方法时先检查父类中是否存在,若存在此方法,则调用子类中的重写方法,否则编译报错。
public class Father{
int a=10;
public void mathon(){
System.out.println("父类的方法");
}
}
public class Son{
public void mather(){
System.out.println("子类的重写方法")
}
}
public class Test{
public static void main(String[] args){
Father f=new Son();//父类Father的变量f接收子类Son的对象
System.out.println(f.a);
f.mathon();//输出“子类的重写方法”
}
}