Java super detailed-15 days study notes

super attention

1. Super calls the parent class's construction method must be placed in the first line of the code.
2. Super can only appear in methods or construction methods of subclasses.
3. Only one of super and this can appear in the constructor.

vs this

1. Different objects represented:

this 调用的本身的对象,

super 调用的父类的对象

2. The premise of use is also different

this  没有继承也可以使用,

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

3. The use of construction methods

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");
		}
	}

Guess you like

Origin blog.csdn.net/yibai_/article/details/114856522