Java super详解 -15天 学习笔记

super注意点

1.super调用父类的构造方法必须放在代码的第一行。
2.super只能出现在子类的方法或者构造方法中。
3.super和this只能有一个出现在构造方法中。

vs this

1.代表的对象不同:

this 调用的本身的对象,

super 调用的父类的对象

2.使用前提也不同

this  没有继承也可以使用,

super 只能在继承的条件下使用

3.构造方法的使用

this    只能调用本构造方法,

super   只能调用父类构造方法
package com.oop;
import com.oop.Demo01.Teacher;


public class Application
{
		public static void main (String[] args){
				
		Teacher teacher =		new Teacher();
		//可以发现new语句输出了父类和子类的无参构造,因为子类的无参构造里面有个隐藏
		teacher.text1("中心");
		System.out.println("=========");
		//调用text2
		teacher.text2();
		
		
		
		}
}
package com.oop.Demo01;
//老师 is person  从属类,子类
public class Teacher extends Person
{
		public Teacher(){
				//隐藏代码,调用了父类的无参构造
				//super();
				//并且super调用父类的构造器必须放在代码的第一行
				System.out.println("Teacher无参构造执行了");
		}
		//创建一个私有的
		private String name = "zhongxin";
		
		//创建个方法
		public void text1(String name){
				System.out.println(name);//代表从String传进来的 中心
				System.out.println(this.name);//本类中的  zhongxin
				System.out.println(super.name);//从父类的 xiaohuanhren
				
		}
		public void print(){
				System.out.println("Teacher");
		}
		public void text2(){
				print();   //Teacher
				this.print();//Teacher,这两个都是输出当前类的
				super.print();//Person
		}
		
}
package com.oop.Demo01;
//类
public class Person
{
		//无参构造
		public Person(){
				System.out.println("Person无参构造执行了");
		}
		
		//创建一个受保护的
		protected String name = "xiaohuangren";
		
		//private 私有的可以被继承但是无法被子类访问
		public void print(){
			
	 	System.out.println("Person");
		}
	}

猜你喜欢

转载自blog.csdn.net/yibai_/article/details/114856522
今日推荐