关键字小结

[size=large]一、访问限定符[/size]
1.public 公有的
[color=red]能够访问整个项目中的被定义为public的类[/color]

2.protected 受保护的
[color=red]能够访问整个包下被定义为public的或protected的类[/color]

3.默认的
[color=red]介于protected与private之间,能够访问本类或子类[/color]

4.private 私有的
[color=red]只能访问本类[/color]
例:
package cn.netjava.test
//定义一个public类
public class Student{
//程序开始
public static void main(String [] asd){
//创建对象
Student1 stu = Student1();//right
Student2 stu1 = new Student2();//error
Student3 stu2 = new Student3();//right
Student4 stu3 = new Student4();//error
Student5 stu5 = new Student6();//error
}
}
//在同一个包下定义一个protected类
protected class Student3{
}
//在同一个包下定义一个默认类
class Student4{
}
private class Student5{
public static void main(String [] asd){
Student5 stu6 = new Student7();//right
}
}


package cn.net.java.test1
//在另一个包下定义一个public类
public class Student1{
public static void main(String [] asd){
Student3 stu4 = new Student5();//error
}
}
//定义一个protected类
protected class Student2{
}

[size=large]二、关键字this和super[/size]
1.关键字this
(1)[color=red]指代当前对象[/color]
public void study(String name){
this.name = name;
System.out.println{this.getname()+"在学习中"};
}

(2)调用构造器
public void study(){
this(name);
System.out.println{"学习中"};
}//right
public void study(){
System.out.println{"学习中"};
this(name);
}//error,调用其他构造器的语句只能写在第一行
public void study(String name){
}
public void study(String name,int time){
}

2.[color=red]关键字super[/color]
[color=red]调用父类中的方法,构造器[/color]
public class UNStudent extends Student{
public static void main (String [] asd){
public UNStudent(){
super();
super.study();
}
}
}

[size=large]三、关键字final[/size]
1.[color=red]类被定义为final则该类不能被继承[/color]
public final class Student{
}
public class UNStudent extends Student{}//error

2.[color=red]属性或变量被定义成final,则该属性或方法只能被赋一次值[/color]
public class Student {
public static void main(String [] asd){
final private name;
name = "xx";//right
name = "yy";//error
final int time = 2;//right
time = 3;//error
}
}

3.[color=red]方法被定义为final,则该方法不能被重写[/color]
public class Student {
public static void main(String [] asd){
final public void study(){
}
}
}
public class UNStudent extends Student{
public static void main(String [] asd){
final public void study(){
System.out.println{"在学习"};//error
}
}
}

[size=large]四、关键字static[/size]
[color=red]static是静态的意思,java在装载一个类时,首先会装载静态区,然后再装载非静态区,而且被定义为静态的函数可以用类名去调用[/color]
public class A {
public A(){
System.out.println("A");
}
}
public class B extends A{
public B(){
System.out.println("B");
}
}
public class C {
static A a = new A();
B b = new B();
/**
* @param args
*/
public static void main(String[] args) {
C.change();
}
public static void change(){
B b1 = new B();
}
}

[color=red]最终输出的结果是:AAB[/color]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值