Java中this和super的用法和区别

super(参数):调用父类中的某一个构造函数(应该为构造函数中的第一条语句)。
this(参数):调用本类中另一种形式的构造函数(应该为构造函数中的第一条语句)。
this的实例:
 1 package com.demo;
 2 
 3 public class Person {
 4     private int age=10;
 5     public Person() {
 6         System.out.println("初始化年龄:"+age);
 7     }
 8     public int GetAge(int age){
 9         //形参与成员名字重名,用this来区分
10         this.age=age;
11         return this.age;
12     }
13     
14 }
15 
16 package com.demo;
17 
18 public class Test {
19     public static void main(String[] args) {
20         Person per=new Person();
21         System.out.println("姓名"+per.GetAge(12));
22     }
23 }

显示结果:

初始化年龄:10
姓名12

super的实例:

1 package com.gouzao1.demo;
2 //父类
3 public class Country {
4     String name;
5     void value(){
6         name="China";
7         
8     }
9 }
 1 package com.gouzao1.demo;
 2 
 3 public class City extends Country{
 4     String name;
 5     void value(){
 6         name="ShangHai";
 7         super.value();//调用父类的方法
 8         System.out.println(name);
 9         System.out.println(super.name);
10     }
11 }

测试:

1 package com.gouzao1.demo;
2 
3 public class TestCity {
4     public static void main(String[] args) {
5         City c=new City();
6         c.value();
7     }
8 }

显示结果:

ShangHai
China

原文地址:https://www.cnblogs.com/yanpingping/p/10543046.html