package
When you see a package, you will think, package? Is it a valuable bag on your shoulder? Ha ha, the blogger is joking. Of course, the package in java.
introduction:
If you create a TestDemo.java file in the company's daily production and development, and your colleagues also create a TestDemo.java file, if you two want to complete the same project, the compiler will respond abnormally due to the same file name. So we brought out the bag here. Creating the same java file in different packages will not report an error.
Packages are a way to organize classes.
The main purpose of using the package is to ensure the uniqueness of the class. In fact, the package is equivalent to a file.
🥇 Import classes in package
If you want to use which class in the package, you can import it.
Similarly, if we want to input a certain number, we need to use the Scanner class. We can find the Java user manual. There is the Scanner class under the util package. In the process of importing the classes in the package, we need to use the import keyword, such as import java.util.Scanner. We have successfully imported the Scanner class in the util package, and when we operate an array, You need to use the Arrays class under the util package, that is, the Arrays class in the import java.util + util package, so that the import is successful. Java brings us many conveniences, such as input, some operations of Arrays, etc. these functions are implemented in the package and do not need to be implemented manually. The import of java package is like the include of C/C + +. It is necessary to import some files into the project. However, there are differences between them. If we don't know that the code needs to use a class under the util package or call the class under the util package, we can also import.java.util, * is a wildcard. If we need to use a class under the util package in the process of writing code, We don't need other operations. Import Java. Util * will automatically import the classes we need instead of all classes under the util package. In C/C + +, you need to import all the files under include.
Code demonstration:
import java.util.Arrays; //Import the array class under util package import java.util.Scanner; //Import the Scanner class under util package public class TestDemo1 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int a = scanner.nextInt(); int []array = {1,2,3,4,5,6}; System.out.println(Arrays.toString(array)); } }
Use wildcards to import classes in the package*
import java.util*;//Import the classes required in the code under the util package public class TestDemo1 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int a = scanner.nextInt(); int []array = {1,2,3,4,5,6}; System.out.println(Arrays.toString(array)); } }
In fact, we can call the classes in the package without the import keyword
public class Test { public static void main(String[] args) { java.util.Date date = new java.util.Date(); // Get a millisecond timestamp System.out.println(date.getTime()); } }
But in the actual process of writing code, we rarely use this.
It is also recommended that you use the relevant classes in the displayed call package. Although wildcards are convenient, they will cause unnecessary trouble on some occasions
import java.util*; import java.sql*; public class Test { public static void main(String[] args) { // There is a class such as Date in util and sql. At this time, ambiguity will occur and compilation error will occur Date date = new Date(); System.out.println(date.getTime()); } }
🥇 Static import
Use import static to import static methods and fields in a package
import java.util.lang.System* public class Test { public static void main(String[] args) { out.println("hello"); } }
Although this looks very concise, it is not recommended, and the readability of the code is not high.
This method is very concise. When calling classes in the package, we should use them according to different situations. We can't blindly ignore the readability of the code for the sake of code simplicity, which is not worth the loss.
import static java.lang.Math.*; public class Test { public static void main(String[] args) { double x = 30; double y = 40; // Static import is more convenient to write // double result = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)); double result = sqrt(pow(x, 2) + pow(y, 2)); System.out.println(result); } }
🥇 Putting classes in packages
Basic rules
-
Add a package statement at the top of the file to specify which package the code is in
-
The package name should be specified as a unique name as far as possible, usually in the inverted form of the company's domain name (e.g. com.bit.demo1)
-
The package name should match the code path. For example, if you create a package of com.bit.demo1, there will be a corresponding path com/bit/demo1 to store the code
-
If a class does not have a package statement, the class is placed in a default package
Create a new package and create a class in the package
1. Create a new package in idea: select SRC -- > New -- > package
2. Name the new package (it's better to name it as the inversion of the company domain name. Bloggers don't have their own company now, let's do it first)
3. Create a new class in the package
🥇 Access control for packages
The blogger said earlier in the article that creating the same file in different packages will eliminate the conflict between files.
package com.bit; public class TestDemo { public static void main(String[] args) { System.out.println("hello world"); } }
package com; public class TestDemo { public static void main(String[] args) { System.out.println("hello world"); } }
The TestDemo.java file in the com package and the TestDemo.java file in the com.bit package will not conflict
When learning java object-oriented programming, we learned the public and private keywords. The member variables and member methods modified by private can only be used in the current class, and other classes cannot be accessed. In the package, if a class or member variable is not modified by public or private, it is the default, that is, it can only be accessed in the package where the current class is located.
Classes in the same package can call each other
package com.bit; public class Test1 { int age; String name; }
package com.bit; public class Test2 { public static void main(String[] args) { Test1 test1 = new Test1(); test1.age = 10; test1.name = "zhangsan"; System.out.println(test1.age); System.out.println(test1.name); } }
Run successfully, output 10 and zhangsan
Calling member variables of classes in different packages
package com.bit; public class Test2 { public static void main(String[] args) { Test3 test3 = new Test3(); test3.age = 10; test3.name = "zhangsan"; System.out.println(test3.age); System.out.println(test3.name); } }
package com.bit.demo; public class Test3 { int age; String name; }
Compilation error
🥇 Common system packages
-
java.lang: system common basic classes (String, Object). This package is automatically imported from JDK1.1.
-
java.lang.reflect:java reflection programming package;
-
java.net: network programming development package.
-
java.sql: support package for database development.
-
java.util: a tool package provided by java. (collection class, etc.) is very important
-
java.io:I/O programming development kit
inherit
🥇 background
When Xiaobai of object-oriented programming sees inheritance, he should want to inherit? Does that mean inheriting millions of homes? Ha ha, it's almost the same.
That is, the father's property becomes the son's, which is inheritance.
According to the idea of inheritance, an animal class is implemented
class Animal{ public int age; //Animal age public String sex; //Animal sex public String name;//Animal name public void eat(){ System.out.println(name + "I am eating"); //Animals have the characteristics of eating } public void sleep(){ System.out.println(name + "Sleeping"); //Animals have the characteristics of sleep } }
Then we are implementing a cat, and a dog class
class Cat{ public int age; public String sex; public String name; public String longtail; public void eat(){ System.out.println(name + "I am eating"); } public void sleep(){ System.out.println(name + "Sleeping"); } public void UpTree(){ System.out.println(name + "Go up the tree"); } } class Dog{ public int age; public String sex; public String name; public String color; public void eat(){ System.out.println(name + "I am eating"); } public void sleep(){ System.out.println(name + "Sleeping"); } public void swim(){ System.out.println(name + "Swimming"); } }
According to the above code, I'm sure careful friends will find that member variables and member methods in animal classes are found in both cats and dogs, because cats and dogs are animals with the same attributes and different attributes.
All three classes have the same eat method and behave exactly the same
All three classes have the same name attribute and have exactly the same meaning
Logically, Cat and Dog are both Animal (is - a semantics)
At this point, we can let Cat and Dog inherit the Animal class respectively to achieve the effect of code reuse
At this time, the inherited classes such as = = Animal are called parent classes, base classes or superclasses. For classes such as Cat and Dog, we are called subclasses. The derived classes are similar to the real son inheriting the father's property. The subclasses will also inherit the fields and methods of the parent class to achieve the effect of code reuse==
🥇 rule of grammar
class Subclass extends Parent class { }
-
Use extends to specify the parent class
-
A subclass in Java can only inherit one parent class (while languages such as C++/Python support multiple inheritance)
-
Subclasses inherit all public fields and methods of the parent class
-
private fields and methods of the parent class are inaccessible in subclasses
-
Instances of subclasses also contain instances of the parent class. You can use the super keyword to reference the parent class.
-
Multiple inheritance is not supported in the java language, that is, a subclass has at most one parent class, but the purpose of multiple inheritance can be achieved through an interface
-
Significance of inheritance: reduce code redundancy and realize code reuse
How to effectively design inheritance: extract the public part of a class and put it into a class. Use extensions to inherit and reuse the code
Realize the above cat and dog inherit animal classes
class Animal{ public int age; public String sex; public String name; public void eat(){ System.out.println(name + "I am eating"); } public void sleep(){ System.out.println(name + "Sleeping"); } } class Cat extends Animal{ public String longtail; public void UpTree(){ System.out.println(name + "Go up the tree"); } } class Dog extends Animal{ public String color; public void swim(){ System.out.println(name + "Swimming"); } } public class TestDemo { public static void main(String[] args) { Dog dog = new Dog(); dog.name = "Wangcai"; dog.eat(); dog.swim(); Cat cat = new Cat(); cat.name = "mimi"; cat.UpTree(); cat.eat(); } } //Operation results: //Wangcai is eating //Wangcai swimming //mimi tree //mimi is eating
We mentioned the super keyword above. Let's see its specific functions according to the code
We know that when we want to create an object, we first allocate memory for it, and then construct a method for it. When we do not define a construction method, the system will automatically create a default parameterless construction method for it.
class Animal{ public int age; public String sex; public String name; public Animal(int age,String sex,String name){ //If you want to initialize the attributes of animals in the Animal class, you need to initialize them, which reminds us of the constructor. However, if you only implement the constructor in the parent class, exceptions will occur in the child class this.age = age; this.sex = sex; this.name = name; } public void eat(){ System.out.println(name + "I am eating"); } public void sleep(){ System.out.println(name + "Sleeping"); } }
The subclass inherits from the parent class and constructs the parent class first
Let's see how it is constructed
class Cat extends Animal{ //Displays the constructor that calls the parent class public Cat(int age,String sex,String name){ super(age,sex,name); } public String longtail; public void UpTree(){ System.out.println(name + "Go up the tree"); } }
Before the subclass inherits from the parent class, super calls the construction method of the parent class to help the parent class construct
High frequency interview questions:
Tell me the difference between this keyword and super keyword?
this keyword
this represents a reference to the current object
**this() * * means calling the constructor of the current class
this.data means to call the member variable in the current class
**this.func() * * means calling member methods in the current class
super keyword
super refers to the reference of the parent class of the current object (this statement is vulnerable, refer to this)
**super() * * means calling the constructor of the parent class
super.data means to call the member variable in the parent class
super.func means to call the member method in the parent class
🥇 protected keyword
I don't know if you have found it. When we call a member variable in a class, it is either public or private. If it is public, the permission will become public, and the member variable to be called can be accessed anywhere. In this way, the encapsulation of the class is lost, and the program we write becomes unsafe, However, if it is a private modification, although it meets the encapsulation of the class, members outside the class cannot access the member properties in the class. So we take the middle and export the protected keyword.
NO | Range | private | default | protected | public |
---|---|---|---|---|---|
1 | Same class in the same package | √ | √ | √ | √ |
2 | Different classes in the same package | √ | √ | √ | |
3 | Subclasses in different packages | √ | √ | ||
4 | Non subclasses in different treasures | √ |
When and what kind of access rights qualifier should we use?
1. We hope that the class should be encapsulated as much as possible to ensure the encapsulation of the class, which means that the internal implementation details are hidden and only the necessary conditions are exposed, which are called by CO callers. If a method in a class can use the private modifier, there should be no protected modifier.
2. In addition, the member variables in the class are generally decorated with private. If you call outside the class now, you can call them with getter and setter methods.
We have learned a lot about inheritance here. Let's take a look at this question: if the parent and child classes use the same member variables, which one do we call when calling?
See the following code:
class Base{ public int a = 1; public int b = 2; } class Derieve extends Test1{ public int a = 3; public void func(){ System.out.println("a = " + a); //Calling member variables in subclasses System.out.println("a = " + super.a); //Call the member variable in the parent class } } public class TestDemo { public static void main(String[] args) { Test2 test2 = new Test2(); test2.func(); } } //Output a = 3 a = 1
When calling the same member variable of the parent class and the child class, the member variable of the child class is called by default. If you want to call the member variable in the parent class, you should modify it with the super keyword. Also, the super keyword cannot be used under static.
🥇 More complex inheritance relationships
Is it complicated? Hahaha, when we generally use inheritance, there should be no more than three layers of inheritance at most. If the number of layers of code to inherit is too large, we should consider code refactoring.
🥇 final keyword
We once learned that when the final keyword modifies a variable or field, it represents a constant (which cannot be modified)
class TestDemo{ public static void main(String[] args) { final int a = 10; a = 20; //report errors System.out.println(a); } }
The final keyword can also be used in a class. If you want a class to be immutable, or if inheritance indicates that a class cannot be inherited
final class Animal{ ·············· } class Cat extends Animal{ //Animal is marked in red, indicating that the animal class cannot be inherited ·············· }
🥇 combination
Similar to inheritance, composition is also a way to express the relationship between classes and achieve the effect of code reuse. For example, it represents a school:
public class Student { ... } public class Teacher { ... } public class School { public Student[] students; public Teacher[] teachers; }
Composition does not involve special syntax (keywords such as extensions), but only takes an instance of one class as a field of another class. This is one of the common ways we design classes. Composition represents has - a semantics. In the example just now, we can understand it as a "inclusion" in a school Several students and teachers. Inheritance represents is - a semantics. In the above example of "animal and cat", we can understand that a cat is also "an animal". We should pay attention to the difference between the two semantics