Java 中的 this 和 super

本文详细介绍了Java编程语言中this与super关键字的使用方法。通过具体代码示例展示了this如何引用当前类实例及调用方法,以及super如何调用父类方法。适合Java初学者了解对象和继承的基本概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



 

this

当前类的实例. 可被用作引用变量(第6行) 或者 方法 (第10行).

 
 1   class Numbers {
 2      private int aNumber = 42;
 3
 4      public int returnANumber() 
 5      {
 6         return this.aNumber;
 7      }
 8      public int returnANumber(int intIn) 
 9      {
10         return (intIn * this.returnANumber()); 
11      }
12
13      public static void main(String[] args) {
14
15         Numbers numberTest = new Numbers();
16  
17         System.out.println("The Number is " +
             numberTest.returnANumber() );
18         //output is: The Number is 42
19         System.out.println("The Number is " + 
             numberTest.returnANumber(2) );    
20         //output is: The Number is 84   
21      }    
22   }

 

super

用于特指引用父类方法
 
class Cat {
   public String name; 
   public Cat() {name = "no nameIn";}
   public Cat(String nameIn) {name = nameIn;}
   public String getName() { 
       return(name + " the Cat"); 
   }           
}          


class Himalayan extends Cat {  
   public Himalayan() {} 
   public Himalayan(String nameIn) {
       name = nameIn;
   }
   public String getName() { 
       return (name + " the Himalayan"); 
   }
   public String getNameAsCat() { 
       return super.getName(); 
   }
   
   public static void main(String[] args) {


      Himalayan cappuccino = new Himalayan("Cappuccino");
 
      System.out.println("The Himalayan name is " + 
        cappuccino.getName() );
      //output is: The Himalayan name is 
      //  Cappuccino the Himalayan
	  
      System.out.println("The Cat name is "
        + cappuccino.getNameAsCat() );    
      //output is: The Cat name is 
      //  Cappuccino the Cat   
   }
}       

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值