为什么需要继承
我现在要有两个类一个 一个是小学生,一个是大学生
代码
小学生
package b;
public class encapsulatio{
public String name;
public int age;
public double score;
public void setscore (double score) {
this.score=score;
}
public void testing() {
System.out.println("小学生"+name+"正在准备考小学数学");
}
public void showinfo() {
System.out.println("pupil name"+name+"age"+age+"score"+score);
}
}
大学生
package b;
public class graduate {
public String name;
public int age;
public double score;
public void setscore (double score) {
this.score=score;
}
public void testing() {
System.out.println("University student"+name+"正在准备考小学数学");
}
public void showinfo() {
System.out.println("pupil name"+name+"age"+age+"score"+score);
}
}
你会发现,这两个类实现的方法没什么不同,
我在主类中
package b;
public class main_ {
public static void main(String[] args) {
encapsulatio e=new encapsulatio() ;
e.name="jacl";
e.setscore(10);
e.showinfo();
}
}
看到了有这个小学生的
那么大学生
encapsulatio e=new encapsulatio() ;
e.name="jacl";
e.setscore(10);
e.showinfo();
graduate a=new graduate() ;
a.name="jacl";
a.setscore(10);
a.showinfo();
这样就很麻烦了那么继承就出马了
继承的细节问题
子类能够继承所有属性和方法,但是私有属性和方法不能在子类直接访问,通过公共方法访问
但可以间接访问,私有属性和方法不能直接在子类中。要通过公有方法访问
我先创建了主类。主类中有公有和私有属性和方法
package b;
public class father_ {//father class
//4attribute
public int n1=100;
protected int n2=200;
int n3=400;
public father_() {//无参构造器
System.out.println("base(....");
}
public void test100() {
System.out.println("test100");
}
protected void test200() {
System.out.println("test200");
}
void test300() {
System.out.println("test300");
}
private void test400() {
System.out.println("test400");
}
}
然后我创建了子类,并在子类中继承主类
package b;
public class graduate extends father_ {
public graduate() {
// TODO Auto-generated constructor stub
System.out.println("graduate");
}
private void sayok() {//子类方法
//非私有的属性和方法可以直接在子类访问,但私有属性和方法不能在子类直接访问
System.out.println(n1+"-------"+n2+"-------"+n3);
test100();
test200();
test300();
test400();
}
}
在用私有方法时The method test400() from the type father_ is not visible
然后我们再创建一个调用的类,就把他命名为main类
package b;
public class main_ {
public static void main(String[] args) {
graduate gra=new graduate();
gra.sayok();
}
}
这里我们调用了graduate.发现它继承的主类中的私有属性和方法都不能访问到
然后我们用公有的在父类中添加。
//父类提供公共方法访问
public int getn3() {
return n4;
}
public void callback400() {
test400();
}
间接调用私有变量和属性
结果
base(....
graduate
100-------200-------400
test100
test200
test300
test400
分享一个快捷键同时选多个
如下图所示,快捷键shift + alt + a 之后按钮鼠标左键往下滑则可实现多行操作的功能,退出则再shift + alt + a 一次即可
ctrl+pagup切换tab
alt +esc在多个屏幕切换焦点