- 前言
- 1.向上转型
- 2,static关键字修饰的函数
- 运行结果
- 3,无static关键字修饰函数
- 总结
前言
今天算是自己第一天开始记录自己的学习情况吧,很快就要去华子入职了,然后Java也算是一个全新的东西需要去学习,之前虽然接触过C++但是其实接触不多,Let begin!今天就记录一下上午学的Java里面的继承与重写
1.向上转型
向上转型可以理解为将子类的对象转换为父类类型的对象(也是今天博客的基础),具体代码如下:
class People{}
class Teacher extends People{}
public class Demo3{
public static void main(String[] args){
People tom = new Teacher();
向上转型一般都是安全的,因为向上转型是具体->抽象的过程,但是向下转型则会带来一些问题,就像你可以说老师是一个人,但你不能说因为他是人,所以是老师。当然了在运用向上转型的过程中也有一些值得注意的地方,比如父类的对象无法调用子类独有的属性和方法。
2,static关键字修饰的函数代码结构为solution1包下面包含三个类,分别是Person类,Student类和Application类,其中Person是父类,Student是子类,而Application是应用类,保证程序中只存在一个main函数,其中Person类代码如下(用static关键字修饰方法):
public class Person
{
public static void test()
{
System.out.println("执行Person类");
}
}
Student类的代码如下:
public class Student extends Person
{
public static void test(int a)
{
System.out.println("执行Person1类");
}
public static void test()
{
System.out.println("执行Student类");
}
}
Application类的代码如下:
public class Application
{
public static void main(String[] args)
{
Person student = new Student();
student.test();
}
}
运行结果
执行Person类 进程已结束,退出代码0
从执行结果中我们可以看出虽然new的对象是一个Student类,但是执行的却是Person类里面的函数。
3,无static关键字修饰函数我们将Person类和Student类中的方法删去static关键字修饰,则运行结果为:
执行Student类 进程已结束,退出代码0
总结
1,当采用static关键字修饰方法时执行的是类(也就是Person类)的方法,当无static关键字修饰时执行的是对象(也就是Student类)的方法。
2,无论是否采用static关键字修饰方法,父类的对象无法调用子类独有的属性和方法(除非重写),在Student类中有test函数的重载,但是student.test(1)并不能执行,因为有形参时test函数是子类特有的函数,但是student可以使用Person类里的重载方法。
3,重写只与非静态方法有关,因为静态方法在类加载的时候就有了。



