王小波:“从话语中,你很少能学到人性,从沉默中却能。假如还想学得更多,那就要继续一声不吭 。”
01 继承
继承——使用extends
关键字在基类的基础上创建新类,新类可以直接复用基类的非private
的属性和方法。
类不是声明为final或者那个类定义为abstract的就能继承。在interface之间也可以声明为extends(多继承)的关系。 注意一个interface可以extends多个其他interface。
class A {
public int m = 0;
private int n = 0;
public void setM(final int m){
this.m = m;
}
}
class B extends A {
}
public class test {
public static void main(String[] args) {
B b;
b.setM(10);
Syaytem.out.println(b.m);
//Syaytem.out.println(b.n);
}
}
02 组合
组合——在新类中创建已有类的对象,通过该对象来调用已有类中的非private的属性和方法;
public class A {
private int m;
public A (int m) {
this.m = m;
}
public int getM() {
return this.m;
}
}
class B {
private A a;
public B () {
this.a = new A(10);
}
public void print() {
System.out.println(a.getM());
}
}
class test {
public static main(String[args]) {
B b;
b.print();
}
}
03 代理
还有一种复用方法是代理——在新类中创建代理,通过代理来操作已有类的非private的属性和方法;就像程序清单3-1那样。
程序清单3-1:
public class A {
private int m;
public A (int m) {
this.m = m;
}
public int getM() {
return this.m;
}
}
class Proxy {
private A a;
public proxy () {
this.a = new A(10);
}
public void print() {
System.out.println(a.getM());
}
}
class B {
private Proxy p;
public B () {
this.p = new Proxy;
}
public void print() {
p.print();
}
}
class test {
public static main(String[args]) {
B b;
b.print();
}
}
代理的模式和组合有点类似,但又有差别——代理成功的隔开了新类(会员)和已有类(店铺)的直接关系,使得已有类的方法不直接暴露在新类面前(组合的方式会将已有类的非private的方法和属性直接暴露在新类中)。
04 final
当不想代码被复用时,使用final关键字。 最终的;决定性的;不可更改的。
使用final的场景有三种,分别是数据、方法和类.
1)final 数据--不可以被修改引用
public class Element{
public static final String version = "1.0";
public final String name;
public Element(final String name)
{
this.name = name;
}
}
final修饰参数:
public void print(final String str) {
// str = "info: " + str; // final修饰的参数是无法在方法内部被再次修改的
System.out.println(str);
}
public void debug(String str) {
str = "debug: " + str;
System.out.println(str);
}
2)final 方法--不可以被继承
在Java类中,所有的private方法都隐式地指定为final的, 是无法被继承者修改的。
程序清单4-2:
class A {
public A () {
say("A: hello!");
}
final public void print(String words) {
System.out.println(words);
}
final public void parentPrint(String words) {
System.out.println(words);
}
}
public class B extends A{
public B () {
say("B: hello!");
}
public void print(String words) {
System.out.println("words);
}
public static void main(String[] args) {
A a = new B();
a.say("hello world!");
a. parentPrint(hello parent!);
B b = new B();
b.say("hello world!");
}
}
3)final 类 --不可以被继承
某个类就是最终的形态了,不应该被继承,使用final关键字来修饰。
final class A {
public A() {
System.out.println("完美!");
}
}
// 无法继承
public class B extends A {
}