类与对象demo
这里先声明一个抽象类Student
- abstract关键字声明该类为抽象类,不可以实例化成对象,可用于实现多态.抽象类中有抽象方法,可在子类实现
- static修饰 静态代码块,在程序执行前,执行一次
public abstract class Student {
public static int xx=0;
static {
xx++;
System.out.println("执行了静态代码块");
}
private int num;
private String name;
private String sex;
private String tel;
public String GetName() {
return this.name;
}
public String GetSex() {
return this.sex;
}
public String GetTel() {
return this.tel;
}
public int GetNum() {
return this.num;
}
public void SetName(String na) {
this.name=na;
}
public void SetSex(String s) {
this.sex=s;
}
public void SetTel(String t) {
this.tel=t;
}
public void SetNum(int nu) {
this.num=nu;
}
public Student(int nu,String na,String s,String t) {
this.name=na;
this.num=nu;
this.sex=s;
this.tel=t;
System.out.println("Student类带参构造");
}
public Student() {
this.name="未知";
this.num=0;
this.sex="未知";
this.tel="未知";
System.out.println("Student类无参构造");
}
public abstract void show();{
}
}
这里声明一个抽象类Student的继承StudentSon
- 在java中用extends表示继承 一个类只能继承一个接口,而一个接口能继承多个接口
- 在java中不是没有多继承!!要分情况
- 同样,实现封装用get set方法
- 构造函数可以重载例如:有参 无参
- 一般类中都有toString方法
public class StudentSon extends Student{
private int money;
public int GetMoney() {
return this.money;
}
public void SetMoney(int m) {
this.money=m;
}
public StudentSon(int m) {
this.money=m;
System.out.println("StudentSon类带参构造");
}
public StudentSon() {
this.money=0;
System.out.println("StudentSon类无参构造");
}
public StudentSon(int nu,String na,String s,String t,int m) {
super(nu,na,s,t);
this.money=m;
System.out.println("StudentSon类带参构造");
}
@Override
public void show() {
System.out.println(super.GetName()+" "+super.GetNum()+" "+super.GetSex()+" "+super.GetTel()+" "+this.GetMoney());
}
public void ex() {
System.out.println("调用子类ex方法");
}
}
这里声明程序入口
- static修饰的方法为该类的静态方法,可以通过类名调用静态方法
- 不能实例化抽象类,抽象类只能用于多态
public static int jia(int a,int b)
{
return a+b;
}
public static void main(String[] args) {
System.out.println(jia(3,4));
StudentSon ss1=new StudentSon();
ss1.show();
StudentSon ss2=new StudentSon(11,"Jam","男","12306",998);
ss2.show();
Student st[]=new Student[2];
st[0]=new StudentSon();
st[0].show();
st[1]=new StudentSon(21,"duu","男","106",9);
st[1].show();
StudentSon ss3=new StudentSon(11,"Jm","女","12306",998);
ss3.ex();
}