关键字final,static break,return的应用

重要的几个关键字
(一):final(最终)
 作用总结:
(1)final修饰变量时不能改变指向(赋值)
   case1:
package com.ywl.practice;
import javax.swing.JPanel;
/*
* 测试类,用于练习上课内容 杨文丽
  */
public class Test {
//主函数
public static void main(String[] args)
{
final JPanel panel1 = new JPanel();
    panel1 = new JPanel();//会报错(因为此处更改了指向)
}
         }
(2)final修饰方法时方法不能重写
     父类Student
package com.ywl.practice;
public class Student {
//方法
public final void play()
{
//打印
System.out.println("学生在玩.....");
}
}
     子类UNStudent
  package com.ywl.practice;
public class UNStudent extends Student {
public void play()//此方法会报错因为父类用final修饰了不能重写方法
{
System.out.println("大学生在玩.....");
}


}
(3)final修饰类时,类此类不能被继承。
   父类:Student
package com.ywl.practice;
public final class Student {
//方法
public void play()
{
//打印
System.out.println("学生在玩.....");
}
}
   子类:UNStudent
package com.ywl.practice;
public class UNStudent extends Student {//报错因为父类用final修饰不能被子类继承



}


(4) 如果在程序中要多次使用的话,则需声明为final
   case2:
package com.ywl.practice;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
/*
* 测试类,用于练习上课内容 杨文丽
  */
public class Test {
//主函数
public static void main(String[] args)
{
final JPanel panel1 = new JPanel();
//创建监听器对象
ActionListener actioner_listener = new ActionListener()
{    //监听方法(监听器里面一定要有)
public void actionPerformed(ActionEvent e)
{
 panel1.setBackground(null);
}
 
};   
}
}
(二)static  静态 指代类中的公共部分(不再属于某个对象私有)
  1.修饰变量时可以直接通过类名直接调用(可以不用对象)
package com.ywl.practice;
public final class Student {
public static int age=10;
//主函数
public static void main(String[] args)
{   
System.out.println("学生的年龄 为"+Student.age);//调用age时直接用类Student调用
 
}
}
   输出结果:学生的年龄为10.
2.修饰方法时可以直接通过类名直接调用(可以不用对象)


package com.ywl.practice;
public final class Student {
//方法
public static int play(){
int i=1, j=2,sum;
sum=i+j;
return sum;
}
//主函数
public static void main(String[] args)
{   int a;
a=Student.play();//直接用类名调用方法
System.out.println(a);
 
}
}
3静态区域内不能直接使用非静态区域内的属性和方法


(三)break和return跳出循环的区别
   break只跳出当前循环
package com.ywl.practice;
public final class Student
{
//主函数
public static void main(String[] args)
{
for(int i=0; i<3;i++)
{
System.out.println("我十一岁");

for(int j=0 ;j<2;j++)
{
System.out.println("我喜欢游泳");
break;
}
}
}
}
输出结果为:我十一岁
            我喜欢游泳
   我十一岁
            我喜欢游泳




   return跳出所以循环
package com.ywl.practice;
public final class Student
{
//主函数
public static void main(String[] args)
{
for(int i=0; i<3;i++)
{
System.out.println("我十一岁");

for(int j=0 ;j<2;j++)
{
System.out.println("我喜欢游泳");
return;
}
}
}
}


输出结果:我十一岁
          我喜欢游泳


    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值