Java programming-sun Xin Java no difficulty lesson3 package, class and method specifier, garbage collection, Interface

Source: Internet
Author: User
Java programming -- Sun Xin Java is not difficult lesson3 package, class and method specifier, garbage collection, Interface

Highlights of this section:
1. Package
2. Class specifiers
3. Method description
4. Destroy the object (demonstration of garbage collection in memory)

5. Interface

//************************************** **************************************** ***

Main content:

1. Functions of packages-- Resolves class name conflicts, similar to the directory system of the file system.

(1) When the package name is used but the package name is not specified during compilation, an error occurs. The error message is as follows:
F: \ Java \ javalesson \ lesson3> javac test. Java

F: \ Java \ javalesson \ lesson3> JAVA Test

//************************************** **************************************** ***

Exception in thread "Main" Java. Lang. noclassdeffounderror: Test (wrong name: Pac
Ktest/test)
At java. Lang. classloader. defineclass1 (native method)
At java. Lang. classloader. defineclass (unknown source)
At java. Security. secureclassloader. defineclass (unknown source)
...
(2) The package name corresponds to a file directory name. If no directory is generated, an error occurs. The error message is as follows:
F: \ Java \ javalesson \ lesson3> JAVA packtest. Test
Error: cannot find or cannot load main class packtest. Test
Solution 1:
Manually create a directory to solve the problem.
F: \ Java \ javalesson \ lesson3> JAVA packtest. Test
Pakage test!
Solution 2: Use javac-D. Parameters
Javac-D. T test. Java // create a folder in the current directory
-D parameter usage:
Generate a package in the current directory

Javac-D. Test. Java

Generate a package in the specified directory

Javac-d e: \ javalesson test. Java
(3) import package
A. Import java. Io. File
B. Introduce the entire package import java. Io. *. When importing all classes, the Java compiler requires additional memory to track class information in the package.
C. classes in the same package can be referenced to each other without the need for import statements
D. the Java lang Package is automatically imported, and the class must be manually imported.
It cannot be referenced directly when it is no longer the same package. The error is as follows:
Test. Java: 10: Error: cannot find the symbol
Test2 test = new Test2 ();
Symbol: Class Test2
Location: class test
2. Class specifiers
(1) Class access specifiers
A. Public
B. Default (when access specifiers are not added)
(2) other modifiers of the class
A. Final
Final class, which cannot be a subclass.

An error occurs when attempting to derive from the final class. The error Inheritance Information is:

//************************************** **************************************** ***

F: \ Java \ javalesson \ lesson3> javac-D. Test. Java
Test. Java: 6: Error: cannot inherit from the final Test2
Class test extends Test2
B. Abstract
C. Compile and use the wildcard javac-D. *. Java
(3) If the class name is not added with a specifier, the default class is not public and cannot be accessed outside the package. The default class can only be accessed in the same package.
Execute the statement:
F: \ Java \ javalesson \ lesson3> javac-D. test2.java
F: \ Java \ javalesson \ lesson3> javac-D. Test. Java

The error message is as follows:

//************************************** **************************************** ***

Test. Java: 5: Error: Test2 is not public in QQ. Test2; cannot access it from external packages import QQ. test2.test
Test. Java: 11: Error: unable to find the symbol Test2 test = new Test2 ();
Symbol: Class Test2
Location: class test
Solution: declare the class as public.
3. Method specifiers
(1) specifier
Method access description
Public
, Protected
And default (when access specifiers are not added)
Other modifiers of the private Method
Static
, Final
, Abstract
, Native
, Synchronized

(2) All methods in the same class can be called.

Access the test program using similar methods, and the running effect is

//************************************** **************************************** ***

F: \ Java \ javalesson \ lesson3> java qq. packtest. Test
Public Method
Protected Method
Default Method
Private Method
(3) The Private method cannot be accessed in the same package, even the inherited class, but the default method can be accessed.
The error message for trying to access the private method is as follows:
F: \ Java \ javalesson \ lesson3> javac-D. test2.java
Test2.java: 12: Error: primethod () You can access private test. primethod () in test ();
(4) classes inherited from different packages can access the public and protected methods, but neither the default and private methods can access
(5) When different packages do not have an inheritance relationship
All methods except the public method are not accessible.

When trying to access methods other than the Public method, the error message is as follows:

//************************************** **************************************** ***

F: \ Java \ javalesson \ lesson3> javac-D. test2.java
Test2.java: 29: Error: promethod () can access protected in Test
Test. promethod ();
Test2.java: 30: Error: defmethod () is not public in test; cannot be accessed from an external package
Test. defmethod ();
Test2.java: 31: Error: primethod () can access private in Test
Test. primethod ();

The access permissions are summarized as follows:


(6) Final Method
A. The final method can be used to ensure that the behavior of a function remains unchanged during the inheritance process and cannot be overwritten.
An error message is as follows:
F: \ Java \ javalesson \ lesson3> javac-D. test2.java
Test2.java: 7: Error: pubmethod () in Test2 cannot overwrite pubmethod () Public void pubmethod () in test as finalb. for efficiency considerations, declare the method as final and let the compiler optimize the call to this method. Note that the compiler will determine the final method and decide whether to optimize it. It is usually declared as final only when the method is small and we do not want it to be overwritten.
C. All the private and static methods in class are actually final.
4. Abstract methods and abstract classes
A. There is no method body in the class, that is, an abstract method. B. classes that contain abstract methods are abstract classes.
C. If a subclass does not implement all the abstract methods in the abstract base class, the subclass also becomes an abstract class.
D. We can declare a class without any abstract method as abstract to avoid generating any objects from this class.
E. constructor, static, private, and final methods cannot be declared as abstract methods.
Common Errors:
A. the abstract method is defined without being declared as an abstract class.
F: \ Java \ javalesson \ lesson3> javac-D. Test. Java
Test. Java: 6: Error: test is not abstract and does not overwrite the abstract method promethod () in test ()
Public class test // extends Test2
B. the abstract class cannot instantiate the object.
Execute the statement:
F: \ Java \ javalesson \ lesson3> javac-D. Test. Java
The error message is as follows:
Test. Java: 44: Error: test is abstract; cannot be instantiated
Test test = new test ();
C. An error occurs when the subclass inherits the abstract method of the parent class and does not overload the abstract method.

The error message is as follows:

//************************************** **************************************** ***

F: \ Java \ javalesson \ lesson3> javac-D. test2.java
Test2.java: 5: Error: Test2 is not abstract and does not overwrite the abstract method promethod () in test ()
Public class Test2 extends Test
5. JNI
A. JNI (Java Native Interface), which allows Java code running inside the Java Virtual Machine (JVM) to work with other programming languages (such as C, C ++, and assembly language) write Applications and libraries for interoperability. B. The biggest advantage of JNI is that it does not impose any restrictions on the implementation of the underlying Java Virtual Machine. Therefore, Java Virtual Machine vendors can add JNI support without affecting other parts of the virtual machine. Programmers can work with all Java virtual machines that support JNI by writing a local (native) Application and library.
C. JNI can be understood as an intermediary between Java and local applications.
D. Native is a method that can be used but cannot be written in Java. Learn more about JNI later.
6. Analysis of the garbage collection mechanism
A. Garbage collection is generally not automatically called. When the memory is insufficient, the system will run garbage collection.
B. To make garbage collection run, you need to explicitly call system. GC ();
C. The garbage collection process is not unique. The running results of the following test code may be different.

The following code is used to test the garbage collection mechanism:

//************************************** **************************************** ***

Class garbage
{
Int index;
Static int CNT;
Garbage ()
{
CNT ++;
System. Out. println ("object" + CNT + "constructed ");
Setid (CNT );
}
Void setid (int id)
{
Index = ID;
}
// Call this function during garbage collection
Protected void finalize ()
{
System. Out. println ("object" + index + "reclaimed ");
}
Public static void main (string [] ARGs)
{
New garbage ();
New garbage ();
New garbage ();
New garbage ();
System. GC (); // call the Garbage Collector explicitly
}

}

//************************************** **************************************** ***

Demo result:
Object1 constructed
Object2 constructed
Object3 constructed
Object4 constructed
Object4 reclaimed
Object3 reclaimed
Object2 reclaimed
Object1 reclaimed
7. Interface--- Solve the coordination problem of developers during the development process and unify the communication between modules.
A. All methods in the interface are abstract and public.
B. In the implementation method of the implementation class, the access permission cannot be lower than the interface access permission.
Otherwise, the error message is as follows:
Sport. Java: 12: Error: Jump () in athlete cannot implement jump () in sport ()
Void jump ()
Attempting to assign lower access permissions; previously public
Sport. Java: 8: Error: Run () in athlete cannot implement run () in sport ()
Void run ()
Attempting to assign lower access permissions; previously public

C. The interface can contain data members. By default, these members are all public static final, that is, public static constants.

//************************************** **************************************** ***

Interface math
{
Double Pi = 3.1415926; // all public static final public static Constants by default
Double roundarea (double radius); // Interface
}
Class arithmetic implements math // implementation Interface
{
Public double roundarea (double radius) // public
{
Return pI * radius;
}
}
Class student
{
Public static void main (string [] ARGs)
{
Arithmetic A = new arithmetic ();
System. Out. println (A. roundarea (3 ));
// Access static member variables
System. Out. println (math. Pi); // OK
System. Out. println (arithmetic. Pi); // OK
System. Out. println (A. Pi); // OK
}
}
D. Interface Implementation 1

The interface implementation DEMO code is as follows:

//************************************** **************************************** ***

Interface sport // define an Interface
{
Void run ();
Void jump ();
}
Class athlete implements sport // implementation Interface
{
// The interface access permission is public
Public void run ()
{
System. Out. println ("sprint ");
}
// If the defined class wants to instantiate the object, all methods in the interface must be implemented.
Public void jump ()
{
System. Out. println ("three hops ");
}

Public static void main (string [] ARGs)
{
Athlete ath = new athlete ();
Ath. Run ();
Ath. Jump ();
}

}

//************************************** **************************************** ***

// Running Effect
F: \ Java \ javalesson \ lesson3> javac sport. Java
F: \ Java \ javalesson \ lesson3> JAVA Athlete
Sprint
Triple hop
E. When interface implementation 2 implements the interface, all methods in the interface must be implemented. Otherwise, an error occurs. The error message is as follows:
Sport. Java: 6: Error: athlete is not abstract and does not overwrite the abstract method jump () in sport ()
Class athlete implements sport // implementation Interface
Sport. Java: 23: Error: No symbol found
Ath. Jump ();
Symbol: Method jump ()
Location: path, a variable of the athlete type

F. An in-depth understanding of the interface concept code is as follows:

//************************************** **************************************** ***

Interface videocard // video card interface
{
Void display (); // display
String getname (); // obtain the product name
}
Class mainboard // Motherboard
{
String strcpu;
Videocard VC; // just define the video card no matter who makes it
Void setcpu (string strcpu)
{
This. strcpu = strcpu;
}
Void setvideocard (videocard Vc)
{
This. VC = VC;
}
Void run ()
{
System. Out. println (strcpu );
System. Out. println (VC. getname ());
VC. Display (); // just call the interface
System. Out. println ("mainboard is running! ");
}
}
Class dmeng implements videocard // The dmeng video card manufacturer implements the video card
{
String name;
// Display
Public void display ()
{
System. Out. println ("dmen's video is working! ");
}
// Obtain the name
Public String getname ()
{
Return name;
}
Public dmeng ()
{
Name = "dmeng video ";
}
Void setname (string Str)
{
Name = STR;
}
}
Class computer // computer
{
Public static void main (string [] ARGs)
{
Dmeng dm = new dmeng (); // graphics card
Mainboard MB = new mainboard (); // Motherboard
MB. setcpu ("Intel's CPU"); // sets the CPU
MB. setvideocard (DM); // sets the video card
MB. Run (); // operation
}

}

//************************************** **************************************** ***

// Running result
Intel's CPU
Dmeng video
Dmen's video is working!
Mainboard is running!
8. Inheritance of interfaces and Classes
A. Java does not support multi-class inheritance.

The Demo code is as follows:

//************************************** **************************************** ***

Class animal
{
// Animal breathing
Void breath (){}
}
Class fish
{// Fish swimming
Void swim (){}
}
Class whale extends animal, fish // error JAVA does not support multi-class inheritance
{
// Whale spray
Void blow (){}

}

//************************************** **************************************** ***

The error message is as follows:
Classextends. Java: 15: Error: require '{'
Class whale extends animal, fish

B. Java allows a class to implement multiple interfaces

//************************************** **************************************** ***

Interface sittable
{
Void SIT ();
}
Interface lie
{
Void sleep ();
}
Class sofa implements sittable, lie // OK allows a class to implement multiple interfaces
{
Public void SIT (){}
Public void sleep (){}
}

C. Java allows multi-inheritance of interfaces

//************************************** **************************************** ***

Interface sittable
{
Void SIT ();
}
Interface lie
{
Void sleep ();
}
Interface chair extends sittable // interface inheritance still uses extends
{
}
Interface sofa extends sittable, lie // OK allows multi-inheritance of interfaces
{
}

D. Java allows multiple interfaces while inheriting classes

//************************************** **************************************** ***

Interface sittable
{
Void SIT ();
}
Interface lie
{
Void sleep ();
}
Interface healthcare
{
Void massage ();
}
Class chair implements sittable
{
Public void SIT (){};
}
Class sofa extends chair implements lie, healthcare // OK allows multiple interfaces while inheriting classes
{
Public void sleep (){};
Public void massage (){};
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.