Java basic knowledge: object oriented

Keywords: Java Attribute Programming

object-oriented

1. Definition of object-oriented
Creating objects can be things or things. In the program, objects are used to map things in reality, and objects are used to describe the relationship between them.
2, Features of object-oriented
Encapsulation

Encapsulation is the core idea of object-oriented, which encapsulates the properties and behaviors of objects without letting the outside world know the specific implementation details.

Inheritance

It mainly describes the relationship between classes. Through inheritance, the function of the original class can be extended without rewriting the original class.

Polymorphism

It refers to the phenomenon that duplicate names are allowed in a program. It refers to that the attributes and methods defined in a class have different meanings in different classes.

Classes and objects

The object-oriented programming idea tries to keep the description of things in the program consistent with the form of things in reality. In order to achieve this, two concepts are proposed in the object-oriented idea. That is, class and object. The object is used to represent the individual of a class of things in reality.

Class definition:

In the thought of object-oriented, the core is object. To create objects in a program. First you need to define a class. Class is an abstraction of an object. It is used to describe the common characteristics and behaviors of a group of objects. Class can define member variables and member methods. Among them, member variables are used to describe the characteristics of objects, also known as attributes; member methods are used to describe the behavior of objects, which can be referred to as methods.

class student{
 int age;//Define int type variable age
 String name;//Define the String type variable name;
 void introduce(){//Defining methods
 System.out.println("Hello everyone, this year"+age+"year,"+"call"+name);
 }
}

A class is defined above. Its student is the class name, and age and name are the member variables. Introduction () is a method that can access the member variable age, name.

Creation and use of objects

You can use the new keyword to create an object in your program.
The format is as follows

Class name object name = new class name ();

Let's take a look at the following example (we have created the method above, now we just need to reference it)

class Exception{
public static void main(String[] args){
   student s1=new student();//create object
   student s2= new student();
   s1.age=13;//assignment
   s1.name=greatly;
   s2.name=Small;
   s1.introduce();//Method of calling object
   s2.introuduce();
 }
}

After execution, the result is as follows. Because the age of s2 is not assigned, the Java virtual machine automatically initializes it, that is, the value is 0

When instantiating an object, the Java virtual opportunity automatically initializes the member variables. For different types of member variables, the Java virtual opportunity gives different initial values.

Member variable type Initial value
byte 0
short 0
int 0
fong 0L
double 0D
char Empty character, '\ u0000'
boolean false
Reference data type null

When the object is instantiated, the first time you call the property of the method, and the second time you call it, null will appear. (when the value of a variable is null, it means that the variable does not point to any object.) if the variable is null, the referenced object is called garbage, which can no longer be called, and becomes a garbage object.

Class design

In Java, objects are created by classes. So it's important to design classes.

Set an animal class, and then define two attributes: name and action

 class animal{
  String name;
   void  shout(){
	  System.out.println(name+"Now I'm calling");
  }
}

Encapsulation of class

(when setting a class, the access of members should be limited and external access is not allowed. This requires class encapsulation.)

Create an object from the animal class designed above and access its members. As shown in the following case

public class Example{
    public static void main(String[] args){
    Animal a1=new animal();
    a1.name="Siberian Husky";
    a1.shout();
    }
}

The operation is as follows:

Class encapsulation refers to the privatization of properties in a class when defining a class, that is, using the private keyword to decorate. Private property can only be accessed in its class. If the outside world wants to access it, it needs to provide some public decoration methods, including getXxx method for getting property value things and setXxx method for setting property value.

package case;
    class animal{
    private String name;//Privatize the property of name
    //The getName and setName of the public method
    private String getName() {
	  return name;
  }  
  public void setName(String suName) {
	  name=suName;
  }
  public  void  shout(){
	  System.out.println(name+"Now I'm calling");
  }
}	
public	class Example{
		public static void main(String[] args){
		   animal su=new animal();
		  su.setName("Siberian Husky");
		  su.shout();
		 }
		   }

Construction method

(the constructor is a special member of the class and is called automatically when the object is instantiated.)

Construction method definition:

  • Method name is the same as class name
  • There is no description of the return value type before the method name
  • You cannot use the return statement to return a value in a method. However, you can write return separately as a summary of the method.
package case;
    class person{
    public  person() {
    System.out.println("Parameterless method called....
    ");
    	}
    }
public	class Example{
	public static void main(String[] args){
			person p1=new person();
	}
}

In a class, you can define not only a construction method without parameters, but also a construction method with parameters.

package case;
class person{
	int age;
	public person(int a) {
		age=a;
	}
public void introduce() {
	System.out.println("This year"+age+"Years old!");
  }
}
    public	class Example{
	public static void main(String[] args){
			person p1=new person(18);
			p1.introduce();
   }
 }

Overload of constructed methods

As with ordinary methods, construction methods can also be overloaded. Multiple construction methods can be defined in a class, as long as the parameter types or the number of parameters of each construction method are different. When you create an object, you can call different construction methods to assign values to different properties.

package case;
class person{
	int age;
	String name;
	public person(int a,String b) {
		age=a;
		name=b;
  }
	public   person(String b) {
	name=b;
  }
	public void person1(int a,String b) {
		age=a;
		name=b;
  }
public void introduce() {
	System.out.println("This year"+age+"Years old!"+"My name is"+name);
  }
}
    public	class Example{
	public static void main(String[] args){
			person p1=new person("greatly");
			person p2=new person(19,"Small");
			p1.introduce();
			p2.introduce();
   }
 }

Format of construction method:

//The first format:
Class class name{
}
//The second format:
Class class name{
  public class name (){
   }
  }

this keyword

Common usage:

  • this keyword can explicitly access the member variables of a class and solve the problem of name conflict with local variables
class student{
String name;
public person(String name){
 this.Name=Name;
 }
 public int getName(){
 return this.Name;
 }
}
  • Call the member method through this keyword.
class student{
public void  this.openMouth(){
 }
}
public void introduce(){
 this.openMouth();
}
  • The constructor is called automatically by the Java virtual machine when the object is instantiated. It cannot be called like other constructor in the program. But you can use this([Parameter1, parameter2 ]) to call other construction methods.
class student{
  public student(){
  Systm.out.println("Parameterless method called...");
  public student(String name){
  this();//Call the parameterless constructor
  System.out.println("Method with parameter called...");
  }
}
public class Example{
   public static void main(String[] args){
   student s1= new student("itcast");//Instanced object
   }
}

Pay attention when using this

  • this can only be used in constructor to call other constructor, not in member variable

  • In the constructor method, the statement using this to call the constructor must be in the first place and can only appear once.

public student(){
String name="tick";
 this(name);//Call the construction method with parameters, because it is not in the first line, compilation error!
}
  • You cannot use this to call each other in two constructor methods of a class.
class Student{
    public student(){
    this("tick");//Call a construction method with parameters
    System.out.println("Parameterless constructor called...");
    }
    public Student(String name){
    this();//Call the parameterless constructor
    System.out.println("Constructor with parameters called...");
    }
}

garbage collection

In addition to waiting for the Java virtual machine to automatically garbage collect, you can also call System.gc () to notify the Java virtual machine of immediate garbage collection. When an object is released in memory, its finalize () method will be called automatically, so you can observe when the object is released by defining the finalize () method in the class.

public student{
//Define finalize method called before garbage collection
   public viid finalize(){
   System.out.println("Objects are recycled as garbage objects...");
   }
}
public class Example{
     public static void main(String[] args){
     //Two creation objects
     student s1= new student();
     student s2=new student();
     //Set the following variables to null;
     s1=null;
     s2=null;
     //Call method for garbage collection
     System,gc(){
        for(int i=0;i,1000000;i++){
          //In order to extend the running time of the program
          }
        }
     }
}

Member inner class

In Java, it is allowed to define a class inside a class. Such a class is called an inner class, and the class where the inner class is located is called an outer class.
Format of inner class

public class name{
   Modifier class name{
   }
}

According to the location of inner class, the modifier and definition method can be divided into member inner class, static inner class, static inner class and method inner class.

In a class, in addition to defining member variables and member methods, you can also define classes. Such classes are called member inner classes. In a member inner class, you can access all members of the outer class.

class Outer{
  private int num=4;//Defining member variables of a class
  //The following code block defines member methods, in which internal classes are accessed
  public void test(){
       Inner inner=new inner();
       inner.show();
  }
  //The following code defines a member inner class
  class Inner{
     void show(){
     //Accessing member variables of external classes in methods of internal classes of members
     System.out.println("num="+num);
     }
  }
}
public class Example{
   public static void main(String[] args){
    Outer outer=new Outer();//Create an external class object
    outer.test();
 }
}

Internal classes can be used in external classes and can access members of external classes, including private. If you want to access internal classes through external classes, you need to create internal class objects through external class objects. The specific format of creating internal class objects is as follows:

External class name. Internal class name variable name = new external class name (). New internal class name ();
class Outer{
  private int num=4;//Defining member variables of a class
  //The following code block defines member methods, in which internal classes are accessed
  public void test(){
       Inner inner=new inner();
       inner.show();
  }
  //The following code defines a member inner class
  class Inner{
     void show(){
     //Accessing member variables of external classes in methods of internal classes of members
     System.out.println("num="+num);
     }
  }
}
public class Example{
   public static void main(String[] args){
    Outer outer o1=new Outer().new Inner() ;//Create an external class object
    outer.show();
 }
}

Local inner class

A local inner class is a class defined in a method, so the outer world cannot be used directly. You need to create an object inside the method and use the class to directly access the members of the outer class, as well as the local variables within the method.

Anonymous Inner Class

Premise: there is a class or interface, where the class can be concrete or abstract
Format:

new class name or interface name (){
   Rewrite method;
};

Essence: it is a subclass anonymous object that inherits the class or implements the interface.
Here is an example.

package case;
import java.lang.reflect.Method;
class Outer { //Create an external class
	   public void method() {
       new Inter() {	
            @Override
			public void show() {//Create inner class
				System.out.println("Pig");	
			}  
		   }.method();//Call method
		  }
	   }
	   //Test class
    public	class Example{
	public static void main(String[] args){
	     Outer o=new Outer();//create object
	     o.method();	//Call method
	}
 }

Re create the Inter interface

package case;

public interface Inter {
 void show() ;	 
 }

If you want to print more data statements, as follows:

package case;
import java.lang.reflect.Method;
class Outer { //Create an external class
	   public void method() {
       Inter i=new Inter() {	
            @Override
			public void show() {//Create inner class
				System.out.println("Pig");	
			}  
		   };
		  i.show();
		  i.show();
		  }
	   }
    public	class Example{
	public static void main(String[] args){
	     Outer o=new Outer();//create object
	     o.method();	//Call method
	}
 }

Summary: curly bracket} after anonymous inner class should be sealed, such as};. If you are creating variables in an anonymous inner class, the format is as follows:

Class name or interface name variable = new class name or interface name (){
override method 
}. method (in interface);

inherit

The concept of inheritance:

In the program, what we continue to describe is the relationship between things. Through inheritance, we can form a relationship system among many things. (you can make the subclass have the properties and methods of the parent, and you can redefine and append the properties and methods in the subclass.)

The parent class is called the base class, the superclass; the child class is called the derived class.

Inherit the characteristics of subclasses: subclasses can have the contents of their parents, and subclasses can also have their own specific contents.

Advantages and disadvantages of inheritance:

Inheritance benefits:

  • Improves code reusability (members of the same class can be placed in the same class)
  • Improve the maintainability of the code (if the code of the method needs to be modified, just modify one place)

Disadvantages of inheritance:

  • Inheritance creates a relationship between classes and enhances the coupling of classes. When the parent class sends changes, the implementation of the subclass has to change, which weakens the independence of the subclass

In Java, class inheritance refers to building a new class on the basis of an existing class. The new class is called a subclass. An existing class is called a parent class, and the child class automatically owns all the inherited properties and methods of the parent class. In a program, you need to use the extends keyword to declare that a class inherits another class.

Inherited format:

public class subclass name extends parent class name ()

Access characteristics of variables in inheritance:

Access a variable in the subclass method: look in the subclass local, member scope, and then the parent member scope class.

Access characteristics of construction methods in inheritance:

  1. By default, all construction methods in the subclass will access the construction methods without parameters in the parent class
    reason:
  • Because the child class inherits the data in the parent class, it may also use the data of the parent class. Therefore, before initializing a subclass, you must first complete the initialization of the parent class data
  • The first statement of each subclass constructor defaults to: super ()
  1. There is no nonparametric construction method in the parent class, only the construction method with parameters
  • Construction method of calling parent class with parameters by using super keyword to display
  • Provide a nonparametric constructor in the parent class.

Access characteristics of member methods in inheritance:

Access a method through a subclass object: in the subclass member scope, in the parent member scope. If not, report the error.

case

//Defining an Animal class
class PersonA{
     String name;//Define the name attribute
     //Defining human behavior
  void action(){
   System.out.println("A Singing");
  }
}
//Define the Biu class to inherit the PersonA class
class Biu extends PersonA{
//Define a method to print name
 public void printName{
     System.out.println("Her name is"+name)
 }
}
//Define test class
public class Example{
   public static void main(String[] args){
   Biu b=new Biu(); //Create an instance object of biu class
   b.name="tearful";//Assign a value to the name attribute of the biu class
   b.PrintName();//Call printName() method of biu class
   b.action();//Call the inherited action() method of the biu class
   }
}

be careful:

1. In Java, classes only support single inheritance, and multiple inheritance is not allowed. That is to say, a class can only have one direct parent class.

class A{}
class B{]
class c extends A,B{}//Class c cannot inherit class a and class b at the same time
  1. Multiple classes can inherit a parent class.
class A{}
class B extends A{}
class C extends A{}//Class b and class c can inherit class a
  1. In Java, multi-level inheritance is possible, that is, the parent of one class can inherit another.
class A{}
class B extends A {} //Class b inherits a, and class b is a subclass of A
class C extends B {}//Class c inherits class b. class c is a subclass of class b and a.

Override method of parent class

In the inheritance relationship, the subclass will automatically inherit the methods defined in the parent class, but sometimes it needs to modify the inherited methods in the subclass, that is, the override of the parent class.

However, it should be noted that the method overridden in the subclass requires that the method overridden by the parent class has the same method name, parameter class table and return value type.

class PersonA{
   void action(){
    System.out.println("She's playing");
  }
}
class biu extends PersonA{
   public static void main(String[] args){
   void action(){
    System.out.println("dance...");
    }
   }
   public class Example{
   Biu b= new Biu();
   b.action();
   }
}

When a subclass overrides a method of a parent class, it cannot use more strict access rights than the overridden method in the parent class. For example: the method in the parent class is public, but the method of the child class cannot be private.

super keyword

Definition: the member used to access the parent class. (identity representing the storage space of the parent class)

  1. Use the super keyword to access the member variables and member methods of the parent class. The specific format is as follows
super. Member variable
 super. Member method ([Parameter1, parameter2...])
package case;
//Defining an Animal class
class Animal{
String name="animal";
//How to define animal calls
void shout() {
	System.out.println("Animals make sounds");
 }
}
//Define cat class to inherit Animal class
class cat extends Animal{
	String name="Felidae";
	//The method of overriding the shout of the parent class
	void shout(){
	 super.shout(); //Access member methods of the parent class
	}
	//Define how to print name
	void biuName() {
		System.out.println("name="+super.name);
	}
}
//Define test class
public class Example {
	public static void main(String[] args) {
		cat c=new cat();//create object
		c.shout();//Call the shop () method overridden by cat object
		c.biuName();//The biuName() method of the object calling cat
	}
}
  1. Use the super keyword to access the construction method of the parent class. The specific format is as follows:
super([Parameter1, parameter2...])
package case;
//Defining an Animal class
class Animal{
//Define the construction method with parameters
   public Animal(String name) {
	   System.out.println("It's a"+name);
   }
}
//Define cat class to inherit Animal class
class Cat extends Animal{
	public Cat() {
		super("Short eared cat");//Call the construction method of the parent class with parameters
	}
}
//Define test class
public class Example {
	public static void main(String[] args) {
		Cat c=new Cat();//Instantiate subclass cat object		
	}
}

abstract class

When defining a class, it is often necessary to define some methods to describe the behavior characteristics of the class, but sometimes the implementation of these methods cannot be determined. (in Java, a method without a method should be defined as an abstract method, and if there is an abstract method in a class, the class must be defined as an abstract class.)

For the case described above, Java allows defining methods without writing the method body, which is called abstract methods. Abstract methods must be decorated with the abstract keyword.

abstract void method (); / / define abstract method ()

When a class contains abstract methods, the class must be decorated with the abstract keyword. A class decorated with the abstract keyword is called an abstract class.

//Define abstract class Animal
abstract class Animal{
  //Define the abstract method shout()
  abstract int shout();
}

Features of abstract classes:

  • Abstract classes and methods must be decorated with abstract keywords
  • There is no abstract method in an abstract class. A class with an abstract method must be an abstract class
  • Abstract class cannot be instantiated, but it can be instantiated through subclass object by referring to polymorphism. This is called abstract class polymorphism
  • The subclass of an abstract class, either rewrites all the methods in the abstract class, or it itself is an abstract class.

Member characteristics in abstract classes:

  • Member variable: can be a constant, because there is a default modifier (public static final)

  • Member variables can be variables or constants

  • The constructor cannot be instantiated. It is used to access the parent class data with the child class

  • Member methods can have abstract methods, restrict subclasses to complete certain actions, or non abstract methods: improve code reusability.

Interface

If all methods in an abstract class are abstract, the class can be defined in another way. It's the interface. Interface is a special class composed of constants and abstract methods, which is a further abstraction of abstract classes.

When defining an interface, you need to use the interface keyword to declare it. Its syntax format is as follows:

[public] interface name [extends interface 1, interface 2...]{
[public] [static] [final] data type constant name = constant value;
[public] [abstract] returns the value abstract method name (parameter list);
  • The interface cannot be instantiated. It needs to refer to the way of polymorphism to realize class object instantiation, which is called interface polymorphism.
    Instantiation form: concrete class polymorphism, abstract class polymorphism, interface polymorphism.

    The premise of polymorphism: inheritance or implementation relationship; method rewriting; parent (class / interface) leading to (child / implementation) class object.

  • Interface implementation class: either rewrite all abstract methods in the interface, or it is an abstract class itself.

    Member characteristics of the interface:

  • Member variable: can only be a constant, it has a default modifier: (public static final)

  • Constructor: there is no constructor for an interface, because the interface is mainly abstract and does not exist. If a class has no parent class, it inherits from the object class by default

  • Member method: can only be abstract method, default modifier: public abstract

package

Package concept and use:

A package is actually a folder, which is used to manage classes by category.

Package definition format:

Package name (multi-level package. Separate)

Compilation and execution of java classes with packages

  • Manual package creation: compile Java files in the previous format - create packages manually - put class files in the bottom of packages - execute with packages

  • Auto build package: javac-d-package name.java

Import (import)

Objective: when using classes under different packages, you need to write the full path of the class. In order to simplify, you need to use the guide package.

Format of the package:

import package name;

Modifier (final, static)

Classification: permission and status modifiers

Permission modifier:

Status modifier:

final:
The final keyword can be used to modify classes, variables, and methods. It has the meaning of "cannot be changed" or "final".

final keyword modifier class
After a class in Java is decorated with the final keyword, it cannot be inherited, that is, it cannot be subclassed.

final keyword modification method
When the method of a class is modified by the final keyword, the subclass of the class cannot override the method.

final keyword modifier variable
In Java, the variables modified by final are called constants, which can only be assigned once. That is to say, once the variables modified by final are assigned, their values cannot be changed. If you assign a value to a variable again, the program will make an error in compilation
It can modify member methods, member variables, and classes.

  • Modifying method: indicates that the method is the final state and cannot be overridden
  • Modifier variable: indicates that the variable is a constant and cannot be assigned
  • A decorated class indicates that it is the final class and cannot be inherited.

final decorated local variable

  • Variables are basic types: final modifies that data values of basic types cannot be changed
  • Variable is reference type: final decoration means that the address value of the reference type cannot be changed, but the content in the address can be changed.

static:

Static means that member methods and member variables can be modified.

static decoration features:

  • All objects of this class are shared
  • It can be called by class name and object.

Static access feature: static member methods can only access static members. But non static member methods can access static and non static member variables and member methods.

It is used to modify the members of a class, such as member variables, member methods, and code blocks. Members modified by static have some special features.

Static variable

In a Java class, you can use the static keyword to decorate member variables, which are called static variables. Static variables are shared by all instances and can be accessed in the form of "class name. Variable name".

class student{
   static String schoolName;//Define the static variable schoolName
}
public class Example{
   public static void main(String[] args){
   student s1=new student();//Create student object
   student s2=new student();
   //Assign values to static variables
   student.schoolName="Hope primary school";
   System.out.println("My school is"+s1.schoolName);
    System.out.println("My school is"+s2.schoolName);
   }
}

The above defines a static variable schoolName in the student class to represent the school of the student, which is shared by all instantiations. Because of the schoolName static variable, it can be called through the instantiated object of student.

The static keyword can only be used to decorate member variables, not local variables, otherwise the compilation will report an error.

public class Student{
//Static member method
   public void study{
       static int num=10;//This line of code is illegal. The compiler will report an error.
   }
}

Static method

As long as the static keyword is added before the method defined in the class, this method is usually called a static method. The same static method can be accessed by the method of "class name. Method name" or by the instantiated object of the class.

public  student{
  public static void sayHellow(){
  System.out.println("hello");
  }
}
class Example{
    public static void main(String[] args){
    student.sayHellow();
    student s1=new student();
    s1.sayHellow();
    }
}

Only static decorated members can be accessed in a static method, because members not decorated with static need to create objects to access. Static methods can be called without creating objects.

Static code block

In Java classes, nuokan line code surrounded by a pair of braces is called a code block. When the class is loaded, the static code block will execute when the class is loaded. Because the class can only be loaded once, the static code block will execute only once. In a program, code blocks are usually used to initialize the class's member variables.

class Example(){
 static{
   System.out.println("The static code block of the test class executes");
   }
   public static void main(String[] args){
   persom p1=new person();
   person p2=new person();
   }
  }
class Person{
   static{
   System.out.println("Peerson Static code block in class executed");
   }
}

polymorphic

Overview: different forms of the same object at different times.

The premise and embodiment of polymorphism:

  1. With inheritance / implementation relationship
  2. Method override
  3. There are parent class references to child class objects

Access characteristics of members in polymorphism:

  • Member variables: compile to the left, execute to the left
  • Member method: compile to the left, execute to the right

Benefits and disadvantages of polymorphism:

Advantage: it improves the extensibility of the program (when defining a method, use the parent type as a parameter, and in the future, use the specific child type to participate in the operation)
Disadvantage: cannot use the specific function of subclass

Polymorphic transformation

  • Transition up: from child to parent (parent references to child objects)
  • Transition down: from child to parent (parent reference to child object)

The difference between super keyword and this keyword

Posted by tomlei on Mon, 22 Jun 2020 23:39:31 -0700