public protected private与this用法

public 修饰的类、成员变量和方法能被所有用户访问。类内类外,包内包外都可以访问。

protected修饰的类、成员变量和方法能被同一包内的用户访问。

private:只能被同类内方法或内部类访问

 

 

  当前类 同一package  子孙类 其他package
public
protected
friendly(default)
private

this有两个作用:一是对其他隐式参数的引用;二是调用其他构造方法。

实例如下:

//package dsa.element;


public class People {
    private String name;
    private String id;
    
    //Constructor
    public People(){
        this("","");
        
    }
        
    public People(String name,String _id){
        this.name = name;
        id = _id;
    }
        
    protected void sayHello(){
        System.out.println("Hello! My name is " + name);
    }
        
    public void sayHello(String name){
        System.out.println("Hello, " + name + "! My name is " + this.name);
    }
        
    //get & set methods
    public void setName(String name){
        this.name = name;
    }
    public void setId(String id){
        this.id = id;
    }
    public String getName(){
        return this.name;
    }
    public String getId(){
        return this.id;
    }
}

 

this("","")表示调用另一构造方法,将name和id都设置为空。

this.name表示类私有成员变量,与setName形参进行区分。

 

 

posted on 2014-03-06 21:06  hadoop-yang  阅读(284)  评论(0编辑  收藏  举报