Simply use the super keyword

super constructor call the parent class

java neutron class does not inherit the parent class constructor, but you can use when we need to use the super keyword to the parent class constructor to call the parent class constructor, the super constructor call the parent class examples are as follows

package test;
class Student{
	int number;
	String name;
	Student(){
	}    //定义一个无参数的构造方法 (建议保留无参数的构造函数,避免利用super关键字时忘记写参数)
	Student(int number,String name){
		this.name = name;
		this.number = number;
	}   // 定义一个含两个参数的构造方法 给number和name初始化
	public int getNumber() {
		 return number;
	}
	public String getName() {
		return name;
	}
}
//建立一个继承Student的UniverStudent类
class UniverStudent extends Student{  
	boolean isMarriage;   //没有初始化赋值 默认为false
	UniverStudent(int number,String name){
		super(number,name);   //调用父类的构造方法初始化number和name
	}
	public boolean getIsMarriage() {
		return  isMarriage;
	}
}

public class Super {
	public static void main(String args[]) {
	//建立一个对象 a
	UniverStudent a = new UniverStudent(2017217954,"leechoy") ;
	int number = a.getNumber();
	String name = a.getName();
	boolean marriage = a.getIsMarriage();
	System.out.print(name+"的学号是:"+number);
	if(marriage==true) {
		System.out.println("已婚!");
	}
	else
		System.out.println("未婚!");
	}
}

operation result:

leechoy的学号是:2017217954未婚!

super call hidden variables and methods

When you create an object in java, in addition to member variables and member variables inherited statement to allocate memory, the hidden member variables have to allocate memory, but the memory does not belong to any object, that memory must be super call, the call usePoint operation. To call the variables and methods examples are as follows:

class Sum{
	int n;
	double f() {
		double sum = 0;
		for(int i =1;i<=n;i++)
			sum+= i;
		return sum;
	}
}
class Average extends Sum{
	double n;
	//重写父类中的f()方法  使继承的父类的f()方法被隐藏
	public double f() {  
		double c;
		super.n = (int)n;  //利用super给隐藏掉的父类的 n变量赋值
		c = super.f();   //调用被隐藏的f()方法
		return c+n;
	}
	double g() {
		double c ;
		c = super.f();   //调用被隐藏的f()方法
		return c-n;
	}
}
public class Super{
	public static void main(String args[]) {
		Average a = new Average();
		a.n = 100.5678;
		double result1 = a.f();
		double result2 = a.g();
		System.out.println("result1 = "+result1);
		System.out.println("result2 = "+result2);
	}
}

operation result:

result1 = 5150.5678
result2 = 4949.4322

Guess you like

Origin blog.csdn.net/qq_41767945/article/details/90743087