Java基础-静态属性,继承

来源:互联网 发布:java文件上传到服务器 编辑:程序博客网 时间:2024/06/06 03:07

Java基础-静态属性-继承

静态属性:

概念:静态属性static属于类,只要类被加载,其就被加载,所以现有静态属性再有实例属性,实例属性被加载,静态属性也一定被加载,静态属性被加载,实例属性不一定被加载。实例属性属于对象。静态属性通过类名直接访问,如:car.count
静态方法:public static void showcarcount(){}
实例方法可以访问静态方法,属性。静态方法不能访问实例方法,因为先加载静态在加载实例
public class car { String brand;//实例属性,属于对象,先有静态属性,而后才有实例属性,所以实例方法可以加载静态方法,静态方法不能加载实例属性 double price; static int count=0;//用static申明是静态属性,只要类呗加载,静态属性就会被加载 /*  * 全参函数  */ public car(String brand, double price) {this.brand = brand;this.price = price;car.count++; } public car(String brand) {this(brand,13200000);} public car(double price) {this.brand = "福特SUV";this.price = price;} public car() {this.brand ="宝马";this.price = 145600;}//实例方法可以加载静态属性 publicvoid run(){System.out.println(this.brand+"在奔跑,售价为"+this.price );} //静态方法不能加载实例属性,因为静态方法加载的时候,实例属性未必已经加载了 public static void showcarcount(){ System.out.println("售出汽车"+car.count+"辆");  } }
public class tester {/** * @param args */public static void main(String[] args) {car c1=new car();car c2=new car("福特SUV");car c3=new car("宝马",123123);c1.run();c2.run();    c3.run();car.showcarcount();}}

继承extends:

extends+类名,继承父类的所有属性和方法,被继承的类叫父类,继承能大量提高复用率,在面向过程的编程语言中复用级别只到函数,面向对象服用级别到类。
object属于lang包下的类,任何java类都有object类,无需导入就可以使用,这是根级别的类。
任何一个java只能继承一个父类(单继承),被继承的类:父类(parent class),超类(super class),基类(base class)继承的类:子类(child class)派生类(derivedclass)
/** * 被继承的类,该类的父类是Object * @author d * */public class animal {String breed;Integer age;Integer weigth;Random r =new Random();//全参构造方法,如果父亲没有有参构造方法则默认生成一个无参构造方法,如果父亲有有参构造方法,子类必须调用父亲的构造方法,用Super来调用public animal(String breed, Integer age, Integer weigth) {super();this.breed = breed;this.age = age;this.weigth = weigth;}public void run(){System.out.println(this.age+"的"+this.breed+"在奔跑");}public void eat(){System.out.println(this.age+"的"+this.breed+"在捕食,捕食后体重为"+this.weigth+r.nextInt(2));} }

/** * @author d * 继承父亲的属性和方法 *用extends */public class tiger extends animal {//自己的实例属性String color;//调用父类的无参构造方法,如果父亲有参构造方法,则通过super进行调用super指向父亲;////public tiger() {////调用父亲的构造方法,//super("东北虎",3,222);////自己的构造方法、,父亲的构造方法优先于自己//this.color="红色";//}//全参构造方法,先调用父亲的构造方法,然后在自己的方法构造(层叠构造方法)先完成父亲的构造,然后是自己的构造public tiger(String breed, Integer age, Integer weigth, String color) {super(breed, age, weigth);this.color = color;}public void work(){System.out.println(this.age+"颜色为"+this.color+"的"+this.breed+"在锻炼");} }


public static void main(String[] args) {tiger t=new tiger("东北虎",3,44,"黄色");t.eat();t.run();t.work();Me m=new Me();//构造方法先调用父亲的构造方法,然后在调用自己的构造方法}


原创粉丝点击