Obeject parent class

This is the 8th day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021.

About the author

  • The authors introduce

🍓 Blog home page: author’s home page 🍓 Introduction: 🥇, a high quality creator in JAVA field, 🎓, a junior in college, participated in various provincial and national competitions and won a series of honors. 🍓 pay attention to me: pay attention to my learning materials, document download all have, regularly update the article every day, inspirational to do a JAVA senior program ape 👨💻.

Anonymous inner class

Inner class: Inside a class another class is defined, called an inner class. An anonymous inner class is an inner class that has no name. To understand the main purpose of inner classes, let’s first look at a piece of code.

interface IMessage{
	public void print(a);
}
class MessageImpl implements IMessage{// Define the interface implementation class
	public void print(a){
		System.out.println("Hello World"); }}class Demo{
	public static void get(IMessage msg){// Accept the interface objectmsg.print(); }}public class TestDemo1{
	public static void main(String args[]){
		IMessage msg = new MessageImpl();// Subclass interface instantiation
		Demo.get(msg);// Pass the MSG object}}Copy the code

If the MessageImpl subclass is now used only once, is it necessary to define it this way?

MessageImpl doesn’t make much sense at this point, but you can use the concept of anonymous inner classes to solve this problem. Anonymous inner classes are based on abstractions and interfaces.

interface IMessage{
	public void print(a);
}
class Demo{
	public static void get(IMessage msg){// Accept the interface objectmsg.print(); }}public class TestDemo1{
	public static void main(String args[]){
		IMessage msg = new IMessage(){// Anonymous inner class
			public void print(a){
				System.out.println("hello,world!"); }}; Demo.get(msg);// Pass the MSG object}}Copy the code

Conclusion: Basically all anonymous inner classes should be done in the form of interfaces or abstract classes.

Use anonymous inner classes in abstract classes

abstract class Message{
	public void print(a){
		System.out.print(this.getInfo());
	}
	public abstract String getInfo(a);
}
class Demo{
	public static void get(Message msg){// Accept the interface objectmsg.print(); }}public class TestDemo1{
	public static void main(String args[]){
		Demo.get(new Message(){
			public String getInfo(a){
				return "www.baidu.com"; }});// Pass the MSG object}}Copy the code

Note: a normal class does not have to have subclasses to inherit, can inherit only abstract classes and interfaces, so continue to use ordinary classes

Subclasses are defined in the form of anonymous inner classes, but are wrong in normal development logic.

Object class introduction

In the definition of Java, except for the Object class, all classes actually have inheritance relationship, that is: if you define a class, there is no default to inherit any parent class, then the default is to inherit the Object class, the following two types of final definition effect is exactly the same.

The no-argument construct of the Object class is dedicated to providing services for subclasses.

Method names type describe
public String toString() ordinary Get object information
public boolean equals(Object obj) ordinary Object comparison
public int hashCode() ordinary Returns the hash code value of an object

ToString ()

The core purpose of toString() is to retrieve object information. Replaces the function of the getInfo() method.

class Person{
	private String name;
	private int age;
	public Person(String name, int age){
		this.name = name;
		this.age = age;
	}
	public String toString(a){
		return "name = " + this.name + ",age = " + this.age ; }}public class TestDemo2{
	public static void main(String args[]){
		Person p = new Person("zsr".18); System.out.print(p.toString()); }}Copy the code

Object comparison equals()

The equals() method of the String class overrides the equals() method of the Object class. The equals() method of the String class overrides the equals() method of the Object class. The default equals() method compares the memory addresses of two objects, but does not match the actual object. Object comparison was also written before, but that was a new method name defined by myself. Today we can give the standard method name: equals().

class Person{
	private String name;
	private int age;
	public Person(String name, int age){
		this.name = name;
		this.age = age;
	}
	public boolean equals(Object anObject){
		if(anObject == null) {return false;
		}
		if(this == anObject){
			return true;
		}
		// Determine if the instance of anObject is a Person
		if( !(anObject instanceof Person)){
			return false;
		}
		// You must change the Object type to Person before you can call the name and age attributes
		Person per = (Person) anObject;
		return this.name.equals(per.name) && this.age == per.age;
	}
	public String toString(a){// Overrides the Object class method
		return "name = " + this.name + ",age = " + this.age ; }}public class TestDemo3{
	public static void main(String args[]){
		Person per1 = new Person("zsr".18);
		Person per2 = new Person("zsr".18);
		//true
		System.out.println(per1.equals(per2));
		//false
		System.out.println(per1.equals("Hello,world!")); }}Copy the code

One caveat, though, is that many people write object comparisons using the following form:

  • public boolean equals(Person anObject)

Because the equals() method of the parent class uses Object, the above method is technically not overridden.

The Object interface references data types

In the previous analysis, Object can receive any Object. Structurally, Object is the parent of all classes, but the concept of Object is not limited to this. It has received all reference data types, including interfaces and arrays.

Use the Object class to receive arrays that have no explicit relationship to Object.

public class TestDemo4{
	public static void main(String args[]){
		Object obj = new int[] {1.3.4};
		int data [] = (int [])obj;// Downward transition
		for(int i = 0; i < data.length ; i++){ System.out.println(data[i]); }}}Copy the code

Receive interface objects, by definition, cannot inherit from a parent class, but since the interface is still a reference type, Object can be used even if there is no inherit class.

interface Message{}
class MessageImpl implements Message{// Define interface subclasses
	public String toString(a){
		return "Hello World"; }}public class TestDemo5{
	public static void main(String args[]){
		Message msg = new MessageImpl();// Upward transition
		Object obj = msg;// Upward transition
		Message temp = (Message) obj;// Downward transition
		System.out.println(temp);//toString()}}Copy the code

In code, this is only a fixed operation concept, but in practice, because of the Obejct class, all operations can be unified, so the previous linked list program, should become very convenient. All data is received using Object, and all Object comparisons (delete, find) can be done using equals().

A wrapper class

In the design of Java, a principle has been advocated: everything is an object, this principle has a loophole in this province, the basic data type is not an object, so this principle has a problem, so if this problem is solved by us, how to solve?

class MyInt{
	private int num;/ / the base class
	public MyInt(int num){
		this.num=num;
	}
	public int intValue(a){
		return this.num; }}public class TestDemo6{
	public static void main(String args[]){
		Object obj = new MyInt(10);// The subclass automatically becomes Object
		MyInt temp = (MyInt) obj;// Downward transition
		intresult = temp.intValue(); System.out.println(result*result); }}Copy the code

The above operation is to change the basic type into the form of an object for operation, but there is a problem: the basic numeric data can be performed mathematically, but the above changed into the form of class, so it must not be directly computed. Since we all think of solutions to the above problems, then Java must have already solved, for this purpose, it specifically provides eight wrapper classes:

byte(Byte),short(Short),int(Integer),long(Long),float(Float),double(Double),boolean(Boolean),char(Character);

The eight packaging categories can be divided into two camps:

Type: Byte,Short,Integer(int),Float,Double,Long;

Object: Boolean,Character(char).

For subclasses of Number, however, we must observe the methods defined in the Number class: ByteVlue (), intVlue(), doubleVlue(), shortVlue(), longVlue(), floatVlue(), get the wrapped value from the wrapped class.

Packing and unpacking

There are two important concepts in the transformation between primitive data types and wrapper classes:

Boxing operation: The constructor of the wrapper class that converts the base data type into a wrapper class, called boxing.

Unpacking: Changes the wrapper class to a primitive data type called unpacking, the xxValue() method in the Number class.

Take int and Integer for example

public class TestDemo{
	public static void main(String args[]){
		Integer var = new Integer(10);/ / packing
		int result = var.intValue();/ / split open a caseSystem.out.println(result*result); }}Copy the code

Take double and double for example

public class TestDemo{
	public static void main(String args[]){
		Double var = new Double(10.0);/ / packing
		double result = var.doubleValue();/ / split open a caseSystem.out.println(result*result); }}Copy the code

This was necessary prior to JDK1.5, but now Java provides automatic boxing and unboxing, and the math of wrapping class objects can be done automatically.

Automatic packing and unpacking

public class TestDemo{
	public static void main(String args[]){
		Integer var = 10;// Automatic boxing
		int result = var;// Automatic unpacking
        // You can use the wrapper class directly for object manipulation
		System.out.println(++var*result);// Automatically perform math operations}}Copy the code

But there’s a little bit of a problem that we’ve actually seen before.

public class TestDemo{
	public static void main(String args[]){
		Integer x = new Integer(10);/ / the new space
		Integer y = 10;/ / into the pool
		Integer z = 10;
		System.out.println(x==y);//false
		System.out.println(x==z);//false
		System.out.println(y==z);//ture
		System.out.println(x.equals(y));//ture}}Copy the code

You also need to consider the difference between equals() and == when using wrapped classes.

Use int or Integer?

  • When receiving data, it must always use an int, while when saving data, it usually uses an Integer

  • Simple Java classes written in the future do not use basic data types, all transposition wrapped classes

Conversion of a string to a primitive data type

One of the biggest advantages offered by wrapper classes is the ability to turn strings into specified primitive data types. Here are a few operations:

Public static int parseInt(String s);

Public static Double parseDouble(String s);

Public static Boolean parseBoolean (String s;

But the character wrapper class does not provide a similar parseCharacter(), because the String class provides a charAt() method that takes the character that defines the index, and each character is one digit in length.

Change a string to an int

public class TestDemo{
	public static void main(String args[]){
		String str = "16";
		int result = Integer.parseInt(str);/ / the String - > intSystem.out.println(result*result); }}Copy the code

Note that all the contents of a character string must consist of digits. If one of the characters is not a number, the following error message is displayed: NumbnerFormatException.

Change the string to double

public class TestDemo{
	public static void main(String args[]){
		String str = "16.";
		double result = Double.parsedouble(str);/ / the String - > intSystem.out.println(result*result); }}Copy the code

Change the string to Boolean data

public class TestDemo{
	public static void main(String args[]){
		String str = "true";
		boolean result = Boolean.parseboolean(str);/ / the String - > intSystem.out.println(result); }}Copy the code

Tip: When wrapping a class with Boolean, if the content in the string is either true or false, it is always false.

The above operation is to change a string to some primitive data type, but conversely, how to change a primitive data type to a string?

Method 1: Any primitive data type that encounters a String becomes a String.

public class TestDemo{
	public static void main(String args[]){
		int num = 100;
		String str = num+"";//int -- >String // generates garbageSystem.out.println(str.length()); }}// Garbage will be generated
Copy the code

Public static String valueOf(type B)

public class BaoZhuangLei{
	public static void main(String args[]){
		int num = 100;
		String str =String.valueOf(num);/ / int - > StringSystem.out.println(str.length()); }}Copy the code

The definition of package

The main purpose of packages in Java programs is to separate files with different functions. In previous code development, all programs were stored in the same directory, which caused problems: If files with the same name appear, then overwrite problems will occur, because files with the same name are not allowed in the same directory, and files with the same name can exist in different directories. The so-called packages are actually folders.

package cn.mldn.demo;/ / define package
public class Hello{
	public static void main(String args[]){
		System.out.println("Hello World"); }}Copy the code

Once defined, the name of the class will be “cn.mldn.demo.hello”, meaning that this is the full name of the class and that the *.class file needs to be stored in the package when the program is compiled, so a packaged compilation operation is provided for ease of development.

Package compiler: javac -d. Class. Java

-d: indicates the directory to be generated according to the package definition

– “.” : Generates *.class in the current directory

Class.java: Compiles the source code

Java cn.mldn.demo.Hello: Java cn.mldn.demo.Hello: Java cn.mldn.demo.Hello: Java cn.mldn.demo. Class “, and in all development, there is no class without a package, as long as the program must have a package.

The package import

Since packages can be used to separate a large program into different functional directories for storage, there will certainly be package import problems between these different packages, and import packages in the program to complete the use of import, the following through a program to demonstrate.

// Define a Message
package cn.mldn.util;/ / packaging
class Massage{
	public String print(a){
		return "Hello World"; }}Copy the code
// Define another class using the Message class
package cn.mldn.text;/ / packaging
import cn.mldn.util.Message;/ / import packages
public class Text{
	public static void main(String args[]){
		Massage msg = newcn.mldn.util.Massage(); System.out.println(msg.print()); }}Copy the code

At this point the above two classes should be compiled in order:

The message.java program should be compiled first: javac — d. message.java;

Test.java: javac — d. test.java: test.java: javac — d. test.java

Text.java:5: Error: Massage is not public in cn.mldn.util; It cannot be accessed from an external packagenew cn.mldn.util.Massage();
                ^
Copy the code

Tip: About the difference between a public class and a class definition class

Public class: the file name must be the same as the class name. Only one Public class definition can exist in a *. Java file.

Class: The file name can be different from the Class name. There can be multiple Class definitions in a *.java file, and the compilation will form multiple *. Class files.

package cn.mldn.util;/ / packaging
public class Massage{
	public String print(a){
		return "Hello World"; }}Copy the code

*.java: javac — d.. Java; *.java: javac — d.. Java;

However, there is a small problem with the above code: the program uses “packages” when importing. Class, but if you want to import multiple classes in a package at the same time, it is too cumbersome to write them separately, so you can use the wildcard “*” to complete the import.

package cn.mldn.text;/ / packaging
import cn.mldn.util.*;/ / import packages
public class Text{
	public static void main(String args[]){
		Massage msg = newcn.mldn.util.Massage(); System.out.println(msg.print()); }}Copy the code

However, it is important to note that there is no difference in the actual performance of using “” or” separate import “in Java, because even if it is used, it means importing the required classes, and not importing the ones that are not needed.

For example, the Message class is now in both packages: cn.mldn.util cn.mldn.info

package cn.mldn.text;/ / packaging
import cn.mldn.util.*;/ / import packages
import cn.mldn.info.*;/ / import packages
public class Text{
	public static void main(String args[]){
		Message msg = newcn.mldn.util.Message(); System.out.println(msg.print()); }}/* Text. Java :6: error: The reference to Message is not explicit, Message and cn.mldn.util match Message MSG = new cn.mldn.util.Message(); ^ * /
Copy the code

The Message class must have the full name of the class when importing two packages at the same time.

package cn.mldn.text;/ / packaging
import cn.mldn.util.*;/ / import packages
import cn.mldn.info.*;/ / import packages
public class Text{
	public static void main(String args[]){
		cn.mldn.util.Message msg = newcn.mldn.util.Message(); System.out.println(msg.print()); }}Copy the code

Access control permission

As I have learned before, private is a kind of access control right, and this access control right is only part of the package. Java provides four access control rights: private, default, protected, and public. The four access control rights are defined as follows:

The scope of private default protected public
Same class in the same package Square root Square root Square root Square root
Different types in the same package Square root Square root Square root
Subclasses in different packages Square root Square root
Non-subclasses in different packages Square root

In fact, public is always accessible, but three main permissions are used for encapsulation: private, default, and protected.

Observe protected access rights

Info.java

package cn.sxau.demo.a;
public class Info {
/ / protected rights
	protected String str = "www.baidu.com";

}
Copy the code

SubInfo.java

package cn.sxau.demo.a;
import cn.sxau.demo.a.Info;
public class SubInfo extends Info{
	public void print(a){
		System.out.println(super.str); }}Copy the code

TestInfo.java

package cn.sxau.testab;
import cn.sxau.demo.a.SubInfo;
public class TestInfo{
	public static void main(String args[]){
		newSubInfo().print(); }}Copy the code

You can see that the SubInfo subclass is not in the same package, but in the same subclass, and can call its subclass.

The error code

package cn.sxau.testab;
import cn.sxau.demo.a.Info;
public class TestInfo{
	public static void main(String args[]){
		System.out.println(newInfo().str); }}/* F:\ Java \javabase\day09>javac -d testinfo.java testinfo.java: STR in Info is protected access control system.out.println (new Info().str); ^ 1 error */
Copy the code

The reason is that STR is protected, so it is not accessible in classes of different classes that are not subclasses.

For permission selection

  • Descriptions of encapsulation are mostly private and rarely protected, both of which are called encapsulation
  • Properties are private, methods are public.

Encapsulation refers to the use of private, protected, and default permissions.

The jar command

Jar is a compressed format file given by Java, that is, the *. Class file can be given to the user as a *. Jar compression package, so that it is convenient to maintain the program, if you want to use Jar, you can directly use the Jar command given by the JDK to complete.

C: Create a new archive

F: Specify the name of the jar file. The user can specify a *.jar file name.

V: Generates standard compressed information

Message.java

package cn.sxau.util;/ / packaging
public class Message{
	public String print(a){
		return "hello world"; }}Copy the code
  1. Compile the message. Java program: javac — d. message. Java, generate the package. Class;
  2. Jar — CVF my.jar cn, a my.jar package is generated;

At this point, my.jar contains the classes you need to use the program

My.jar and mytest.java are now in the same directory. However, the contents defined in my.jar cannot be found, because in Java each *.jar file belongs to a separate CLASSPATH path, and the CLASSPATH must be configured for use.

You need to configure SET CLASSPATH=. F:\java\javabase\day09\my.jar

// Define a test class to call my.jar
package cn.sxau.test;
public class MyTest{
	public static void main(String args[]){
		cn.sxau.util.Message msg = newcn.sxau.util.Message(); System.out.println(msg.print()); }}/* Execute F:\ Java \javabase\day09> Java cn.sxau.test.MyTest hello world */
Copy the code