This article will give you a detailed introduction of inheritance, overloading, and coverage in Java. I hope this article will be helpful to you.
1. Inheritance: Use the extends keyword to directly inherit a class.
When the Sub class and Base class are in the same package, the Sub class inherits the public/protected/default-level variables and methods in the Base class.
Variables and methods at the public/protected level are inherited in different packages.
2. Overload: If two methods have the same name but different parameters, such a method is overloaded by another method.
Same method name
The parameter type of the method. The number order must be at least one different.
3. Overwrite: if a method is defined in a subclass, its name, return type, and parameter signature exactly match the name, return type, and parameter signature of a method in the parent class, the subclass method overwrites the method of the parent class.
The return type and parameter signature of the Method Name of the subclass must be consistent with that of the parent class.
Subclass methods cannot reduce the access permissions of parent Methods
The subclass method cannot throw more exceptions than the parent method.
If the constructor of the parent class is not explicitly called in the constructor of the subclass (super is used), the non-argument constructor of the parent class is executed.
Instance
Java code
<SPAN>
The Code is as follows: |
Copy code |
Class Super { Static int stat = 1; Int nonStat = 2; Static int statMethod (){ Return 3; } Int nonStatMethod (){ Return 4; } } Public class Sub extends Super { Static int stat = 10; Int nonStat = 20; Static int statMethod (){ Return 30; } Int nonStatMethod (){ Return 40; } Public static void main (String [] args ){ Super s = new Sub (); System. out. println ("Static is" + s. stat ); System. out. println ("Non-Static is" + s. nonStat ); System. out. println ("Static method is" + s. statMethod ()); System. out. println ("Non-Static method is" + s. nonStatMethod ()); Sub sub = (Sub) s; System. out. println ("Static is" + sub. stat ); System. out. println ("Non-Static is" + sub. nonStat ); System. out. println ("Static method is" + sub. statMethod ()); System. out. println ("Non-Static method is" + sub. nonStatMethod ()); } } </SPAN> Output result: <SPAN> Static is 1 Non-Static is 2 Static method is 3 Non-Static method is 40 Static is 10 Non-Static is 20 Static method is 30 Non-Static method is 40 |