Java基础-类的封装,成员变量的访问及隐藏

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wanlong360599336/article/details/60141840

1.给类的变量封装,加访问权限(get(),set())步骤:

2.成员变量的访问权限:

2.1 建第一个包,类里面设置几个变量,有public,protected和默认类型(什么都不加)

2.2 建第二个包,去引用第一个包,然后去继承第一个包里面的类,如下图:

2.3  引用第二个包,开始调用其类的变量和方法


具体实现调用的代码:

import cn.test.SecondPackage.*;
public class EncapsulationStudy {

	public static void main(String[] args) {
		System.out.println("--------成员变量的访问---------");
		SecondClass scc=new SecondClass();
		scc.print();
		
		System.out.println("--------成员变量的隐藏---------");
		Father f=new Father();
		System.out.println(f.str);
		Son s=new Son();
		//由于Son继承了Father类,同时输出str值,可以看出Son输出的是自己的值,并没有输出Father的str值,等于是覆盖了,或者说是隐藏了父类的str值
		System.out.println(s.str);
		//如果需要访问父类的str值,这个时候可以在Son类通过super来进行访问
		s.ShowFatherStr();
	}
}

class Father{
	String str="Father String";
}

class Son extends Father{
	String str="Son String";
    void ShowFatherStr(){
    	//通过super来去访问父类的变量
		System.out.println(super.str);
	}
}

//类的封装,属性的访问
class HumanInfo
{
	String name;
	int age;
	String address;
	double weight;
	double height;
	public String getName() {
		return name;
	}
	public int getAge() {
		return age;
	}
	public String getAddress() {
		return address;
	}
	public double getWeight() {
		return weight;
	}
	public double getHeight() {
		return height;
	}
	public void setName(String name) {
		this.name = name;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public void setWeight(double weight) {
		this.weight = weight;
	}
	public void setHeight(double height) {
		this.height = height;
	}
}


猜你喜欢

转载自blog.csdn.net/wanlong360599336/article/details/60141840