Method overrides
/*method overrides (commonly used in inheritance) definitions: it refers to the relationship between the subclass and the parent class, and the subclass overrides the method of the parent class. Two method return value, method name, parameter list must be exactly the same! Cause: In Java, subclasses can inherit methods from the parent class without having to rewrite the same method. But sometimes subclasses do not want to inherit the parent class's methods, but want to make some changes, which requires a method of rewriting. Method overrides are also called method overrides. */classperson{Private intAge ; PrivateString name; Public intGetage () {returnAge ;} Public voidSetage (intAge) { This. Age =Age ;} PublicString GetName () {returnname;} Public voidSetName (String name) { This. Name =name;} PublicString GetInfo () {return"The name is:" +getname () + ", Age is:" +getage ();}}classStudentextendsperson{PrivateString School; Public voidSetschool (String school) { This. School =School;} PublicString Getschool () {returnSchool;} PublicString GetInfo () {return"The name is:" +getname () + ", Age is:" +getage () + ", the School is:" +school;}//this overrides the method of the parent class} Public classoveriding { Public Static voidMain (String args[]) {Student Student=NewStudent (); Person Person=NewPerson (); Person.setage (40); Person.setname ("Zhang San"); Student.setage (23); Student.setname ("John Doe"); Student.setschool ("Yu Ying School"); System.out.println (Person.getinfo ()); System.out.println (Student.getinfo ()); } }
Method overloading
/*method overload definition: The same method name in the same class, the parameters are different (the parameter type is not the same or the number of parameters is not the same) reason: in the programming process, is to adhere to the programming specifications, which requires the naming of the method is meaningful, and some methods may face , there will be a list of unused parameters, which will use the overload, so that the meaning of the method can be expressed, but also that these methods are related methods, convenient to call. Therefore, the method overload, to a large extent for the readability of the program, even if not, it will not prevent the program to run. */classcar{ Public voidMYF (intA) {System.out.println ("I am Method 1"));} Public voidMYF (String a) {System.out.println ("I am Method 2");} Public voidMYF (String a,string b) {System.out.println ("I am Method 3");}} Public classOverloading { Public Static voidMain (String args[]) {Car car1=NewCar (); Car1. MYF (2);//The first method is dropped according to the parameters in the methodCar1. MYF ("Medium");//depending on the parameters in the method, the second method is dropped .Car1. MYF ("Zhong", "state");//according to the parameters in the method, the third method is dropped . } }
java--method Overrides and overloads