java封装的理解及使用及 No enclosing instance of type j is accessible. Must qualify the allocation with an

来源:互联网 发布:罪夜之奔 知乎 编辑:程序博客网 时间:2024/05/29 08:40
/**
*A:封装概述
* 是指隐藏对象的属性和实现细节,仅对外提供公共访问方式。


*B:封装好处
* 隐藏实现细节,提供公共的访问方式
* 提高了代码的复用性
* 提高安全性。
*C:封装原则
* 将不需要对外提供的内容都隐藏起来。
* 把属性隐藏,提供公共方法对其访问。
*
*
*
*private关键字的概述和特点(这个可以帮助封装)
*private关键字特点
* a:是一个权限修饰符
* b:可以修饰成员变量和成员方法
* c:被其修饰的成员只能在本类中被访问
*
*
*把成员变量用private修饰
*提供对应的getXxx()和setXxx()方法,get方法需要返回值,set不需要
*private仅仅是封装的一种体现形式,不能说封装就是私有
*

*/

public class demon {public static void main(String[] args) {Person p = new Person();p.name = "张三";//调用姓名属性并赋值//p1.age = 17;//调用年龄属性并赋值 错  不能这样做,private类型,只能在Person中访问//p1.speak();//调用行为p.setAge(17);System.out.println(p.getAge());}static class Person {String name;//姓名private int age;//年龄 私有//对私有变量的访问方法,对私有变量进行封装,并提供set,get方法public void setAge(int a) {//设置年龄if (a > 0 && a < 200) {age = a;//this.age = a,这个下次说}else {System.out.println("你不是地球人");}}public int getAge() {//获取年龄return age;}public void speak() {System.out.println(name + "..." + age);}}}
/***
* 相关问题,new person()时一直提示错误
* No enclosing instance of type j is accessible.
* Must qualify the allocation with an enclosing instance of type j (e.g. x.
* 已经用new实例化了这个类,为什么还不行呢?
*
* 查了一下
* 我写的内部类是动态的,以public class开头(没有用static修饰)。(刚开始这样写的)
* 而主程序是public static class main。
* 在Java中,类中的静态方法不能直接调用动态方法。
* 要在静态类中调用该类的内部类必须把这个内部类修饰为静态
*
* 还有一个方法就是把person这个内部类设为外部类就ok了,
*
* 刚开始学问题问题很多,在此记录下来,供大家做个参考
* */


0 0
原创粉丝点击