package tom.jiafei;public class Father { int height; protected int money; public int weight; public Father(int m) { money = m; } protected int getmoney() { return money; } void setMoney(int newMoney) { money = newMoney; }}import tom.jiafei.Father;public class Jerry extends Father{ public Jerry() { super(20); } public static void main(String[] args) { Jerry jerry = new Jerry(); jerry.height = 12; jerry.weight = 200; jerry.money = 800; int m = jerry.getmoney(); jerry.setMoney(300); System.out.println("m="+m); }}
父类protected int money; 子类Jerry jerry = new Jerry();jerry.money = 800;这里错了,protected的访问权限是本类,同包,继承类,你的Jerry是new出来的新对象
代码太乱了,看起来很吃力。protected声明的变量可以在同一个包、同一个类里面访问。不同包的话只能是子类才能访问。
我做了如下例子:
package cn.itlaobing.hibernate.test;
/**
* ClassName: A <br/>
* Function: TODO 功能描述 <br/>
* date: 2017年6月14日 上午9:30:58 <br/>
*
* @author Mmmmm
* @version
* @since JDK 1.8
*/
public class A {
protected int i = 0;
}
/*******************************************************************************
* Copyright (c) 2010, 2030 www.mahao.cn
*
* Licensed under the Apache License, Version 2.0 (the "License");
*******************************************************************************/
package cn.itlaobing.hibernate.test.b;
import org.junit.Test;
import cn.itlaobing.hibernate.test.A;
/**
* ClassName: B <br/>
* Function: TODO 功能描述 <br/>
* date: 2017年6月14日 上午9:32:13 <br/>
*
* @author Mmmmm
* @version
* @since JDK 1.8
*/
public class B extends A {
@Test
public void testExtend(){
B b = new B();
b.i=10;
System.out.println(b.i);
}
}