JAVA notes (object oriented)

Java object oriented and process oriented

Both procedure oriented and object oriented (OO) are ideas for software analysis, design and development. They guide people to analyze, design and develop software in different ways. In the early stage, there was the thought of process oriented. With the expansion of software scale and the improvement of problem complexity, the disadvantages of process oriented are more and more obvious. Object-oriented thought has emerged and become the mainstream way at present. Both run through all stages of software analysis, design and development. The corresponding object-oriented is called object-oriented analysis (OOA), object-oriented design (OOD) and object-oriented programming (OOP). C language is a typical process oriented language, and Java is a typical object-oriented language.

The same point: both are the way of thinking to solve problems and the way of code organization.
Difference: there are three characteristics from features to objects: encapsulation, inheritance and polymorphism. However, process oriented has no inheritance and polymorphism. In terms of problem solving:

Object oriented is used in the macro and process oriented in the micro. Process oriented is suitable for simple transactions that do not need cooperation.

Connection: facing the object includes facing the process, and the two complement each other.

Java inheritance

Inheritance is a cornerstone of java object-oriented programming technology because it allows the creation of hierarchical classes. Inheritance can be understood as the process by which an object obtains properties from another object. In Java, class inheritance is single, that is, a subclass has only one parent class. For example, if class A is the parent of class B and class B is the parent of class C, we also call C a subclass of a, and class C inherits from class A.

Inheritance keyword: extends # implements

By using the keyword extends, a subclass can inherit all the attributes of the parent class except the private attribute.

By using the keyword implements, it is used when the class inherits the interface

package java05;
/**
 * inherit
 * @author Administrator
 *
 */
public class JavaInherit {

	public static void main(String[] args) {
		Student stu1=new Student("java", "Zhang San", 168);
		stu1.rest();
		stu1.study();
		//instanceof binary operator, left object, right class
		System.out.println(stu1 instanceof Person);
		System.out.println(stu1 instanceof Student);


	}
}
//Parent class person class
class Person{
		String name;
		int height;
		public void rest() {
			System.out.println("Take a break!!");
		}
	}
//Inherit keyword extends subclass Student class
class Student extends Person{
	   String major;
	   public void study() {
		   System.out.println("I study in blue cloud java");
	   }
	public Student(String major,String name,int height) {
		super();
		this.major = major;
		this.height=height;
		this.name=name;
		
	}
	  
	
   }

Note:

         1. Parent classes are also called superclasses, base classes, derived classes, and so on.

         2.Java is too complex and the system is difficult to maintain.

         3. In Java, there is no multi inheritance for classes, and there is multi inheritance for interfaces. There is only single inheritance, not multiple inheritance like C + +. Multiple inheritance can cause confusion, making the inheritance chain

         4. A subclass inherits from the parent class and can get all the properties and methods of the parent class (except the construction method of the parent class), but it may not be directly accessible (for example, the properties and methods private to the parent class).

          5. If you define a class without calling extends, its parent class is: Java lang.Object.  

Java override and overload

Override: overriding is a subclass's rewriting of the implementation process of the allowed access methods of the parent class! Neither return value nor formal parameter can be changed. That is, the shell remains unchanged and the core is rewritten! The advantage of rewriting is that subclasses can define their own specific behavior as needed. That is, the subclass can implement the methods of the parent class as needed. In the object-oriented principle, rewriting means that any existing method can be rewritten

  

package java05;
/**
 * Method rewrite
 * @author Administrator
 *
 */

public class JavaMethodOverride {
	public static void main(String[] args) {
		Vehicle v1=new Vehicle();
		Vehicle v2=new Horse();
		Vehicle v3=new Plane();
		v1.run();
		v2.run();
		v3.run();
		v1.stop();
		v3.stop();
		
	}	
}


//Parent class
class Vehicle{
	//run method
	public void run() {
		System.out.println("run");
	}
	//stop method
	public void stop() {
		System.out.println("Stop");
	}
}
//Subclass 1
class Horse extends Vehicle{
	//Override method run
	public void run() {
		System.out.println("Run fast");
	}
}
//Subclass II
class Plane extends Vehicle{
	public void run() {
		System.out.println("Fly in the sky!!!");
	}
	public void stop() {
		System.out.println("The plane crashed!!!!!");
	}
}

Method override rule
* the parameter list must be exactly the same as that of the rewritten method; The return type must be exactly the same as that of the overridden method;
* the access permission of the subclass method must be greater than or equal to that of the parent method. For example, if a method of the parent class is declared public, overriding the method in the child class cannot be declared protected.
* member methods of a parent class can only be overridden by its subclasses. A method declared final cannot be overridden. Methods declared as static cannot be overridden, but can be declared again.
* if the subclass and the parent class are in the same package, the subclass can override all methods of the parent class, except those declared as private and final.
* if the subclass and the parent class are not in the same package, the subclass can only override the non final methods declared as public and protected by the parent class.
* the overridden method can throw any non mandatory exception, regardless of whether the overridden method throws an exception or not. However, the overridden method cannot throw new mandatory exceptions, or mandatory exceptions that are broader than those declared by the overridden method,
* otherwise. Constructor cannot be overridden. If you cannot inherit a method, you cannot override it.

Overload: overloading is in a class. The method names are the same, but the parameters are different. The return type can be the same or different. Each overloaded method (or constructor) must have a unique list of parameter types. Only constructors can be overloaded

package javabiji;
/**
 * heavy load
 */

import org.omg.CORBA.PUBLIC_MEMBER;

public class JavaOverLoad {
	public static void main(String[] args) {
		//Method overload seen
		System.out.println();
		System.out.println(1);
		System.out.println(3.5);
		
		
			
	}
	/*Summation method*/
	public static int add(int n1,int n2) {
		int sum=n1+n2;
		return sum;
	}
	
	/*The same method name and different parameter lists constitute an overload*/
	public static int add(int n1,int n2,int n3) {
		int sum=n1+n2+n3;
		return sum;
    }
	/*The same method name and different parameter types constitute an overload*/
	public static double add(double n1,int n2) {
		double sum=n1+n2;
		return sum;
	}
	
	/*Compilation error, only the return value is different, which does not constitute an overload*/
//	public static double add(int n1,int n2) {
//		double sum=n1+n2;
//		return sum;
//	}
	
	/*Compilation error. Only the parameter names are different, which does not constitute an overload*/
//	public static double add(int n2,int n1) {
//		double sum=n1+n2;
//		return sum;
//	}
}

 

Overload rule

* the overloaded method must change the parameter list;

* overloaded methods can change the return type;

* the overloaded method can change the access modifier;

* overloaded methods can declare new or broader check exceptions;

* methods can be overloaded in the same class or in a subclass.

Java polymorphism

     

Polymorphism refers to the same method call, which may have different behaviors due to different objects. In real life, the specific implementation of the same method will be completely different. For example: it is also the method of calling people's "rest". Zhang San is sleeping, Li Si is traveling, and programmer Zhao is typing the code

Advantages of polymorphism

    1. Eliminate coupling between types

    2. Replaceability

   3. Extensibility

   4. Interface

   5. flexibility

   6. Simplification

Three necessary conditions for the existence of polymorphism

1. Inherit

2. Rewrite

3. A parent class reference points to a child class object

When calling a method in a polymorphic way, first check whether there is the method in the parent class. If not, there will be a compilation error; If so, call the method with the same name of the subclass.

The advantage of polymorphism: it can make the program have good expansion, and can deal with all kinds of objects in general.

package javabiji;
/**
 *Object oriented polymorphism
 * @author Administrator
 *
 */
public class JavaPolym {

	public static void main(String[] args) {
		Animal a1=new Cat();//Upward can automatically transform
		//The method is called according to the type passed, which greatly improves the extensible type of the program
		animalCry(a1);
		
		Animal a2=new Dog();
		
		animalCry(a2);//a2 is the compilation type, and the Dog object is the running type
		
		//When writing a program, if you want to call a method of runtime type, you can only carry out mandatory type conversion, otherwise the compilation will report an error
//		Dog dog =(Dog)a2;
//		dog.seeDoor();
		
		//Downward transformation
//		Animal c=new Cat();
//		Dog d3=(Dog)c;
//		d3.seeDoor();
	}
	
	
	//With polymorphism, you only need to let the added class inherit the Animal class
	static void animalCry(Animal a) {
		a.shout();
	}
	
	
	/*
	 * //If there is no polymorphism, you need to write a lot of method overloads. Each time you add the same animal, you need to overload the shot method of one animal
	 *  static void animalCry(Dog d) {
	 *         d.shout(); 
	 *   }
	 *  static void animalCry(Cat c) { 
	 *        c.shout();
	 *  }
	 */}
class Animal{
	public void shout() {
		System.out.println("Animal cry!");
	}
}
class Cat extends Animal{
	public void shout() {
		System.out.println("Woof, woof!");
	}
	

}
class Dog extends Animal{
	public void shout() {
		System.out.println("Meow meow!");
	}
	public void seeDoor() {
		System.out.println("Watch the door");
	}

}

Output result:

Woof! Woof!
Meow meow!

Java encapsulation

In the object-oriented programming method, Encapsulation refers to a method to wrap and hide the implementation details of abstract function interfaces.

Encapsulation can be considered as a protective barrier to prevent the code and data of this class from being randomly accessed by the code defined by the external class.

To access the code and data of this class, it must be controlled through strict interface.

The main function of encapsulation is that we can modify our implementation code without modifying the program fragments that call our code.

Proper encapsulation can make the code easier to understand and maintain, and also enhance the security of the code.

Advantages of packaging

1. Good packaging can reduce coupling.

2. The internal structure of the class can be modified freely.

3. You can control the member variables more accurately.

4. Hide information and realize details.

Steps to implement Java encapsulation

1. Modify the visibility of attributes to restrict access to attributes (generally private), for example:

public class Person {
    private String name; 
    private int age;

}

In this code, the name and age attributes are set to private, which can only be accessed by this class, and can not be accessed by other classes, so the information is hidden.

2. Provide external public method access for each value attribute, that is, create a pair of value assignment methods for accessing private attributes, for example:

public class Person{  
  private String name;   
  private int age;  
  public int getAge(){  
    return age;  
  }  
 public String getName(){ 
     return name;   
 }
  public void setAge(int age){   
   this.age = age;    
  }
   public void setName(String name){  
    this.name = name;   
   }
}

this keyword is used to solve the conflict of the same name between the instance variable (private String name) and the local variable (name variable in setName(String name)).

In the above example, the public method is the entry for the external class to access the member variables of this class.

In general, these methods are called getter and setter methods.

Therefore, any class that wants to access private member variables in the class must pass through these getter and setter methods. Attention!!! The get() method of boolean type starts with is!!!

The following example shows how the variables of EncapTest class are accessed:

/* F File name: runencap java */
public class RunEncap{  
 public static void main(String args[]){      
   EncapTest encap = new EncapTest();    
   encap.setName("James");   
   encap.setAge(20);     
   encap.setIdNum("12343ms");     
   System.out.print("Name : " + encap.getName()+ " Age : "+ encap.getAge());  
  }
}

Java Interface

Interface (English: Interface), an abstract type in JAVA programming language, is a collection of abstract methods. Interfaces are usually declared as interfaces. A class inherits the abstract methods of the interface by inheriting the interface.

Interfaces are not classes. The way of writing interfaces is very similar to that of classes, but they belong to different concepts. Class describes the properties and methods of an object. Interface contains the methods to be implemented by the class.

Unless the class implementing the interface is an abstract class, the class should define all methods in the interface.

The interface cannot be instantiated, but it can be implemented. A class that implements an interface must implement all the methods described in the interface, otherwise it must be declared as an abstract class. In addition, in Java, interface types can be used to declare a variable. They can become a null pointer or be bound to an object implemented by this interface.

Similarities between interface and class:

  • An interface can have multiple methods.
  • Interface files are saved in In the file ending in java, the file name uses the interface name.
  • The bytecode file of the interface is saved in class.
  • The bytecode file corresponding to the interface must be in the directory structure matching the package name.

Differences between interfaces and classes:

  • Interfaces cannot be used to instantiate objects.
  • Interface has no constructor.
  • All methods in the interface must be abstract methods.
  • An interface cannot contain member variables except static and final variables.
  • The interface is not inherited by the class, but implemented by the class.
  • The interface supports multiple inheritance.

 

Declaration of interface

The declaration syntax format of the interface is as follows:

[visibility] interface Interface name [extends Other class names] {
        // Declare variable
        // Abstract method
}

The Interface keyword is used to declare an Interface. The following is a simple example of an Interface declaration.

/* File name: nameofinterface java */
import java.lang.*;
//Introduction package

public interface NameOfInterface
{
   //final, static fields of any type
   //Abstract method
}

The interface has the following characteristics:

 1. Access modifier: can only be public or default.

 2. Interface name: the same naming mechanism as the class name.

 3. Extensions: the interface can inherit multiple.

 4. Constant: the attribute in the interface can only be a constant. It is always decorated with public static final. Not writing.

 5. Method: the method in the interface can only be: public abstract. If omitted, it is also public abstract.

example

/* File name: animal java */
interface Animal {

   public void eat();
   public void travel();
}

Interface implementation

When a class implements an interface, the class should implement all the methods in the interface. Otherwise, the class must be declared abstract.

Class uses the implements keyword to implement the interface. In the class declaration, the implements keyword is placed after the class declaration.

To implement the syntax of an interface, you can use this formula:

... implements Interface name[, Other interfaces, Other interfaces..., ...] ...

example

/* File name: mammalint java */
public class MammalInt implements Animal{

   public void eat(){
      System.out.println("Mammal eats");
   }

   public void travel(){
      System.out.println("Mammal travels");
   } 

   public int noOfLegs(){
      return 0;
   }

   public static void main(String args[]){
      MammalInt m = new MammalInt();
      m.eat();
      m.travel();
   }
} 

The compilation and operation results of the above examples are as follows:

Mammal eats
Mammal travels

When rewriting the method declared in the interface, you need to pay attention to the following rules:

  • When a class implements the method of an interface, it cannot throw a mandatory exception. It can only throw the mandatory exception in the interface or in the abstract class that inherits the interface.
  • Class should maintain consistent method names when overriding methods, and should maintain the same or compatible return value types.
  • If the class implementing the interface is an abstract class, there is no need to implement the methods of the interface.

When implementing the interface, you should also pay attention to some rules:

  • A class can implement multiple interfaces at the same time.
  • A class can only inherit one class, but can implement multiple interfaces.
  • One interface can inherit another interface, which is similar to the inheritance between classes.

Interface inheritance

An interface can inherit in a similar way to another class. Interface inheritance uses the extends keyword, and the child interface inherits the methods of the parent interface.

The following Sports interfaces are inherited by Hockey and Football interfaces:

 

// File name: sports java
public interface Sports
{
   public void setHomeTeam(String name);
   public void setVisitingTeam(String name);
}

// File name: football java
public interface Football extends Sports
{
   public void homeTeamScored(int points);
   public void visitingTeamScored(int points);
   public void endOfQuarter(int quarter);
}

// File name: hockey java
public interface Hockey extends Sports
{
   public void homeGoalScored();
   public void visitingGoalScored();
   public void endOfPeriod(int period);
   public void overtimePeriod(int ot);
}

 

The Hockey interface declares four methods and inherits two methods from the Sports interface. Therefore, the class implementing the Hockey interface needs to implement six methods.

Similarly, a class that implements the Football interface needs to implement five methods, two of which come from the Sports interface.

Multiple inheritance of interfaces

In Java, multiple inheritance of classes is illegal, but interfaces allow multiple inheritance,.

In multiple inheritance of interfaces, the extends keyword only needs to be used once, followed by the inherited interface. As follows:

public interface Hockey extends Sports, Event

The above program fragments are legally defined sub interfaces. Unlike classes, interfaces allow multiple inheritance, while Sports and events may define or inherit the same methods

An interface without any method is called a tag interface. The tag interface is mainly used for the following two purposes:

Create a public parent interface:

Just like the EventListener interface, which is a Java API extended by dozens of other interfaces, you can use a tag interface to establish the parent interface of a set of interfaces. For example, when an interface inherits the EventListener interface, the Java virtual machine (JVM) knows that the interface will be used for the proxy scheme of an event.

To add a data type to a class:

This situation is the original purpose of the marked interface. The class implementing the marked interface does not need to define any interface methods (because the marked interface has no methods at all), but the class becomes an interface type through polymorphism.

Java package

In order to better organize classes, Java provides a package mechanism to distinguish the namespace of class names.

Function of package

  • 1 organize classes or interfaces with similar or related functions in the same package to facilitate the search and use of classes.
  • 2 like folders, packages are stored in a tree directory. The class names in the same package are different, and the class names in different packages can be the same. When calling classes with the same class name in two different packages at the same time, the package name should be added to distinguish them. Therefore, the package can avoid name conflicts.
  • 3 packages also limit access rights. Only classes with package access rights can access classes in a package.

Java uses the package mechanism to prevent naming conflicts, access control, and provide search and location class es, interfaces, enumerations, and annotation s.

The syntax format of the package statement is:

package pkg1[.pkg2[.pkg3...]];

For example, a thing Java file its contents

package net.java.util
public class Something{
   ...
}

Then its path should be net / java / util / something java saved like this. The function of package is to classify and save different java programs, which is more convenient to be called by other java programs.

A package can be defined as a set of interrelated types (classes, interfaces, enumerations and annotations), which provide access protection and namespace management functions for these types.

Here are some packages in Java:

  • java.lang - packing basic classes
  • java.io - functions containing input and output functions

Developers can package a set of classes and interfaces and define their own package. Moreover, in the actual development, it is worth advocating to do so. When you complete the class implementation by yourself, grouping the relevant classes can make it easier for other programmers to determine which classes, interfaces, enumerations and annotations are relevant.

Since the package creates a new namespace, there will be no naming conflict with any names in other packages. Using the package mechanism, it is easier to implement access control and make it easier to locate related classes.

create package

When creating a package, you need to give the package a suitable name. Later, if another source file contains the classes, interfaces, enumerations or annotation types provided by the package, the declaration of the package must be placed at the beginning of the source file.

The package declaration should be on the first line of the source file. Each source file can only have one package declaration, and each type in this file applies to it.

If a package declaration is not used in a source file, the classes, functions, enumerations, comments, etc. will be placed in an unnamed package.

example

Let's look at an example that creates a package called animals. Lowercase letters are usually used to avoid conflicts with class and interface names.

Add an interface to the animals package:

/* File name: animal java */
package animals;

interface Animal {
   public void eat();
   public void travel();
}

Next, add the implementation of the interface to the same package:

package animals;

/* File name: mammalint java */
public class MammalInt implements Animal{

   public void eat(){
      System.out.println("Mammal eats");
   }

   public void travel(){
      System.out.println("Mammal travels");
   } 

   public int noOfLegs(){
      return 0;
   }

   public static void main(String args[]){
      MammalInt m = new MammalInt();
      m.eat();
      m.travel();
   }
} 

Then, compile the two files and put them in a subdirectory called animals. Run with the following command:

import keyword

In order to use the members of a package, we need to explicitly import the package in the Java program. Use the "import" statement to complete this function.

In the java source file, the import statement should be located after the package statement and before the definition of all classes. There can be no or multiple, and its syntax format is:

package javabiji;
//Guide package method I
import java.util.Date;
//import java.util.Scanner;
import java.util.*;//Importing all the packages under this package in package import method 2 will reduce the compilation speed, but will not reduce the running speed

public class JavaPackage {

	public static void main(String[] args) {
		//This refers to Java sql. Date
		Date now;
		//java.sql.Date and Ava util. The date class has the same name and needs a full path
		java.util.Date  now2=new java .util.Date();
		System.out.println(now2);
		//java. Classes with different names in util package do not need a full path
		Scanner input=new Scanner(System.in);

	}

}

If a class in a package wants to use another class in this package, the package name can be omitted.

  

 

 

 

 

 

 

Tags: Java

Posted by kevin777 on Tue, 24 May 2022 19:51:36 +0300