day08 final关键字&面向对象——多态&抽象类、方法&向上、向下转型

day08

final关键字

最终的不可更改的

特点:

1)修饰类,类不能被继承

2)修饰方法,方法不能被重写

3)修饰成员变量(变为常量),值不能修改,名字大写,声明同时给常量赋值

main方法中

1)修饰基本数据类型,基本数据类型不能改

2)修饰引用类型,内存地址不能被改变,但地址内的值可以

@Override//注解

String的底层是final修饰的char类型的数组

String就是final修饰的常量类

所以String被称为字符串常量

面向对象三要素——多态

没有继承就没有多态,生成的对象在调用父类的方法时,如果方法被子类重写,则调用的时子类重写的方法

代码当中体现多态性,父类引用指向子类对象

父类名 对象名 = new 子类名();

Java中,有两种形式可以实现多态:继承和接口

方法的重载实现的是编译时的多态性(也成为前绑定),重写实现的是运行时的多态性(也称后绑定)

抽象类

定义:

抽象类不能被实例化,它的作用是提供给其他类进行继承

抽象关键字abstract

public abstract class Father{
    public abstract void fun1();
    String name;
    private int age;
    public void fun2(){
        
    }
}
public class Son extends Father{
    public void fun1(){
        
    }
}

特点

抽象方法

被abstract修饰,只有方法签名,没有方法体,可以被子类重写

public abstract void fun1();

接口

接口只有方法签名

interface声明接口关键字

接口特点

接口只有方法签名和静态常量

接口的变量默认补全public final static

接口签名方法,默认使用public abstract修饰

一个类可以实现多个接口,Java中遵循单继承多实现,先继承后实现

被继承后必须重写所有方法

public class Son extends Father implements IPerson,IPlayer{
    public void fMethod(){
    }
    public void IPMethod(){
    }
    public void IPlMethod(){
    }
}

byMyself

接口可以继承接口,继承时可以不用重写父类接口的方法(可能因为接口做不到实例化)

类继承接口必须重写方法,否则报错

接口之间不能相互实现

优点:

解决单继承的问题(类只能单继承,但可以实现多个接口)

接口可以实现并行开发

便于重构

向上转型

父类类型创建子类对象

在此有Father类,Tom主类和Son类继承Father类

Father f = new Son();

向下转型

只有Object有向下转型的可能

Son f = new Father();//不能成功
Son f = (Son) new Father();//语法可以通过,但不建议
//先不说

本文作者:小彤在努力

本文链接:https://www.cnblogs.com/xiaoto9426/p/16783050.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   小彤在努力  阅读(14)  评论(0编辑  收藏  举报
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起
  1. 1 Scarborough Fair Sarah Brightman
Scarborough Fair - Sarah Brightman
00:00 / 00:00
An audio error has occurred.

Are you going to Scarborough Fair

Parsley, sage, rosemary and thyme

Remember me to one who lives there

Remember me to one who lives there

He once was a true love of mine

Tell him to make me a cambric shirt

Parsley, sage, rosemary and thyme

Without no seams nor needle work

Without no seams nor needle work

Then he'll be a true love of mine

Tell him to find me an acre of land

Parsley, sage, rosemary and thyme

Between salt water and the sea strands

Then he'll be a true love of mine

Then he'll be a true love of mine

Tell him to reap it with a sickle of leather

Tell him to reap it with a sickle of leather

Parsley, sage, rosemary and thyme

Parsley, sage, rosemary and thyme

And gather it all in a bunch of heather

And gather it all in a bunch of heather

Then he'll be a true love of mine

Then he'll be a true love of mine

Are you going to Scarborough Fair

Parsley, sage, rosemary and thyme

Parsley, sage, rosemary and thyme

Remember me to one who lives there

Remember me to one who lives there

He once was a true love of mine

He once was a true love of mine

点击右上角即可分享
微信分享提示