在Java中super和this的區別

來源:互聯網
上載者:User

標籤:end   itext   bsp   允許   nbsp   屬性   pac   變數   his   

摘要:在Java中我們會時常用到super及this的用法,現在我主要來區分一下super.和this.及superL()及this()之間的區別,來對它們的認識和瞭解:

  1.this的用法在Java中:

①:this.:this加點指此時代表當前對象,能操作當前類裡面的所有屬性及方法以及父類繼承而來能被存取修飾詞允許的屬性和方法。

  super.:此時指代當前對象類的父類對象部分,不能操作到本類的屬性和方法,能操作到父類的能被父類存取修飾詞允許的屬性和方法,只有當本類中調用被重寫前的效果時使用super.的方法。

  文法:this.成員名  或者  this. 方法名

  例:這是this加點使用

public class DemoThis {private String name;private int age;public DemoThis() {this.print();// 你可以加上this來調用方法,}public DemoThis(String name, int age) {this.name = name;this.age = age;//這裡就必須使用this加點的方法來區分,this.name就指代當前的屬性name;} public void setName(String name) {this.name = name; // 此處必須指明你要引用成員變數}public void setAge(int age) {this.age = age;}public void print() {System.out.println("Name=" + name + " Age=" + age); // 在此行中並不需要用this,// 因為沒有會導致混淆的東西}}

  例:super加點的使用,

package com.lov.lianxiText;public class DemoThis {//父類private String name;private int age;public DemoThis() {}public void print() {System.out.println("哈哈哈哈。。。。。");}}

  

package com.lov.lianxiText;public class Demo extends DemoThis {//子類public Demo(){}public void print(){super.print();//只有這個時候用super.方法,其他我們基本用this.方法System.out.println("嘿嘿嘿.......");}}

 總結:有上面我們可知道,this.的使用範圍要比super.的範圍更大,除了上面要看重寫前的效果能super,我們都是用this.的方法。

2:this()與super()

 ①this()和super()都是使用只能使用於構造方法中,

 ②this()調用本類的構造,如果括弧內有形參,則是調用本類的與之相對應參的構造方法;super()調用父類指定的構造方法,

 ③都只能寫在構造方法的第一句;

 ④super()可以不寫,在不寫的時候會預設調用父類的無參構造,

 ⑤this()與super()不能共存,兩者只能使用一個。

 

在Java中super和this的區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.