派趣吧

如何对super和this进行比较?

明星时间:1年前阅读:21

  package test;

public class ThisTest {

private int i=0;

//第一个构造器:有一个int型形参

ThisTest(int i){

this。i=i+1;//此时this表示引用成员变量i,而非函数参数i

System。

  out。println("Int constructor i——this。i:

"+i+"——"+this。i);

System。out。println("i-1:"+(i-1)+"this。i+1:"+(this。i+1));

//从两个输出结果充分证实 了i和this。

  i是不一样的!

第二个构造器:有一个String型形参

ThisTest(String s){

System。out。println("String constructor:

"+s);

第三个构造器:有一个int型形参和一个String型形参

ThisTest(int i,String s){

this(s);//this调用第二个构造器

//this(i);

/*此处不能用,因为其他任何方法都不能调用构造器,只有构造方法能调用他。

但是必须注重 :就算是构造方法调用构造器,也必须为于其第一行,构造方法也只能调

用一个且仅一次构造器!*/

this。i=i++;//this以引用该类的成员变量

System。out。println("Int constructor:

"+i+" "+"String constructor:

"+s);

public ThisTest increment(){

this。

  i++;

return this;//返回的是当前的对象,该对象属于(ThisTest)

public static void main(String[] args){

ThisTest tt0=new ThisTest

(10);

ThisTest tt1=new ThisTest("ok");

ThisTest tt2=new ThisTest(20,"ok again!");

System。

  out。println(tt0。increment()。increment()。increment()。i);

//tt0。increment()返回一个在tt0基础上i++的ThisTest对象,

//接着又返回在上面返回的对象基础上i++的ThisTest对象!

运行结果:

Int constructor i——this。

  i:

10——11

String constructor:

ok

String constructor:

ok again!

Int constructor:

21

String constructor:

ok again!

14

注重 :this不能用在static方法中!所以甚至有人给static方法的定义就是:没有this的方法!虽然夸张,但是却充分说明this不能在static方法中使用!

//1。

  super运用在构造函数中

class test1 extend test{

public test1()。。。{

super();//调用父类的构造函数

public test1(int x){

super(x);//调用父类的构造函数,因为带形参所以super 也要带行参

//2。

  调用父类中的成员

class test1 extend test{

public test1(){}

public f(){//假如父类里有一个成员喊 g();

super。g();//super引用当前对象的直接父类中的成员

上一篇:这是什么意思Super?

下一篇:Super star的意思?

派趣吧

我来回答