The hiding of member variables and the overriding of methods
Goods.java
Public class Goods { publicdouble weight; Public void oldsetweight (double w) { Weight=W; System.out.println ("double type weight=" +weight); } Public Double Oldgetprice () { double price = Weight*10; return Price ; }}
Cheapgoods.java
public class cheapgoods extends Goods { public int weight; public void newsetweight (int W) {weight =W; SYSTEM.OUT.PRINTLN ( "int weight=" +weight); public double Newgetprice () { double price = Weight*10; return price; }}
Example5_3.java
Public classExample5_3 { Public Static voidMain (String args[]) {cheapgoods cheapgoods=NewCheapgoods (); //cheapgoods.weight=198.98 is illegal because the weight of the subclass object is already an int typeCheapgoods.newsetweight (198); System.out.println (The value of the weight of the object Cheapgoods is: "+cheapgoods.weight); System.out.println ("Cheapgoods to calculate the price with a subclass of the new offer method:" +Cheapgoods.newgetprice ()); Cheapgoods.oldsetweight (198.987);//The subclass object calls the inherited method operation to hide the double type variable weightSystem.out.println ("Cheapgoods uses inherited methods (no offers) to calculate price:" +Cheapgoods.oldgetprice ()); } }
Subclass overrides for inheriting a parent class method
University.java
Public class University { void enterrule ( double math,double中文版, double Chinese) { double total=math+english+Chinese; if (total>=180) System.out.println ("scores" +total+ "to reach the university's lowest admission line"); Else System.out.println ("scores" +total+ "not meet the minimum admission line of the University");} }
Importantuniversity.java
Public class extends university{ void enterrule (double math,double中文版, double Chinese) { double total=math+english+Chinese; if (total>=220) System.out.println ("scores" +total+ "to reach the key university admission Line"); Else System.out.println ("scores" +total+ "failed to reach the key university admissions line");} }
Example5_4.java
Public classExample5_4 { Public Static voidMain (String args[]) {Doublemath=64,english=76.5,chinese=66; Importantuniversity Univer=Newimportantuniversity (); Univer.enterrule (Math,english,chinese); //calling the overridden methodmath=89; 中文版=80; Chinese=86; Univer=Newimportantuniversity (); Univer.enterrule (Math,english,chinese); //calling the overridden method }}
Java subclass inherits the shadowing of the parent class member variable, overriding the Implementation method