Fundamentals of Java - object oriented

catalogue

Java object oriented

object

The idea of object-oriented reflects that the information of the object concerned by people is gathered on a specific object. People understand objects through their properties and behaviors.

For a specific object, such as an iPhone 16, there are many objects with the same properties or behaviors as this phone in the world. In order to facilitate classifying them and extracting their same properties and behaviors, we call the abstract concept classified as class.

Class name object name = new Class name();
People LiLei = new People();

class

Class definition:

  • Class is an abstraction of the same or similar objects. It is a template of objects. It describes the behavior and state of a class of objects.

  • A class is a collection of objects with the same properties and methods (behaviors)

Attributes are the characteristics of objects. Each attribute of each object has a specific value. As we mentioned above, an object is a specific and definite thing. It is the value of the object attribute that distinguishes different objects. For example, we can distinguish a person by his physical characteristics.

Behavior, in the computer, we realize the behavior of the object through methods, and the method of the object is the operation of the object. For example, people can walk, cry, learn, etc. are human behaviors, that is, human methods.

Define class

  1. Defines the class name, which is used to distinguish different classes. In the following code, public class is followed by the class name. Class is the keyword to declare the class. The class name is followed by braces, which contain some information about the class. Public is the permission modifier.
public class Class name {
    //Define attribute part (member variable)
    Type of property 1;
    Type of property 2;
    ...
    //Define method section
    Method 1
    Method 2
    ...
}

  1. Write the properties of the class. Objects need to be represented by attributes. The definition of an attribute is written in braces after the class name. When defining an attribute, the type of the attribute should be specified. One or more attributes can be written in a class. Of course, you can not define attributes.

  2. Write methods for classes. The method is also written in braces. You can define one or more methods, or you can not define methods.

A class can contain the following types of variables:

  • Local variables: variables defined in methods, construction methods, or statement blocks are called local variables. Variable declaration and initialization are in the method. After the method ends, the variable will be destroyed automatically.
  • Member variables: member variables are variables defined in the class and outside the method body. This variable is instantiated when the object is created. Member variables can be accessed by methods in a class, constructor methods, and statement blocks of a specific class.
  • Class variable: also called static variable. Class variable is also declared in the class, outside the method body, but must be declared as static type.

The scope of a local variable is limited to the method that defines it. The scope of member variables is visible within the whole class.
At the same time, in the same method, there can be no local variables with the same name; In different methods, there can be local variables with the same name.
When a member variable and a local variable have the same name, the local variable has a higher priority. You can write code to verify it.

Construction method

Each class has a constructor, which will be called when creating the object of the class. If there is no constructor defined, the Java compiler will provide a default constructor. When creating an object, at least one constructor is called.

The name of the constructor must be the same as the class name. A class can define multiple constructors.

//With the same name as the class, you can specify parameters without return value
public Construction method name(){
//setup code
}

public class People{
    //Nonparametric construction method
    public People(){

    }
    //Construction method with one parameter
    public People(int age){

    }

    //Constructor that initializes all properties
    public People(double h, int a, int s){
        height = h;
        age = a;
        sex = s;
    }


}

People XiaoMing = new People(168, 21, 1);

  • If the constructor is not written when defining a class, the system will generate a parameterless constructor by default, which will do nothing.

  • When there are specified construction methods, the system will not add parameterless construction methods.

  • Overload of construction method: for multiple methods with the same method name but different parameters, the corresponding method will be automatically selected according to different parameters when calling.

References and object instances

Object object=new Object();

So is the variable object really an object object object? In fact, it just creates a reference to an object object object. If students have learned C language, here, like pointers, the reference of the object object object saved by the variable object points to the object object.

References and object instances
When creating a new object instance, you need to set an object name for the object instance, like this

Object object=new Object();
copy
So is the variable object really an object object object? In fact, it just creates a reference to an object object object. If students have learned C language, here, like pointers, the reference of the object object object saved by the variable object points to the object object.


 ----------           ----------
 | object |---------> | Object |
 ----------           ----------
 |        |           |        |
 ----------           ----------
 |        |           |        |
 ----------           ----------
 |        |           |        |
 ----------           ----------
 |        |           |        |
 ----------           ----------

Object object1 = new Object();
Object object2 = object1;
System.out.println(object1 == object2);


true

The result of running is true, indicating that the memory addresses of object1 and object2 are the same (= = will compare whether the memory addresses of the two objects are the same). They actually refer to the same object. If you change the internal attributes of object1 object, the attributes of object2 will also change. Students can come down to verify this.

static

  • Static member

Members modified by static in Java are called static members or class members. It belongs to the whole class, not to an object, that is, it is shared by all objects of the class. Static members can be accessed directly by class name or by object name.

public class StaticTest{
    public static String string="shiyanlou";
    public static void main(String[] args){
        //Static members can be accessed directly without instantiation
        System.out.println(StaticTest.string);
        //If you do not add the static keyword, you need to access it in this way
        StaticTest staticTest=new StaticTest();
        System.out.println(staticTest.string);
        //If you add the static keyword, the above two methods can be used
    }
}

  • Static method
    The method modified by static is a static method. The static method does not depend on the object and can be called without instantiating the class. Because it can be called without instantiation, it cannot have this, nor can it access non static member variables and non static methods. However, non static member variables and non static methods can access static methods.

final

The final keyword can modify classes, methods, properties, and variables

  • If final modifies a class, the class is not allowed to be inherited and is the final class
  • final modifier method, the method is not allowed to be overwritten (overridden)
  • final modified attribute: the attribute of this class will not be implicitly initialized (the initialization attribute of the class must have a value) or assigned in the constructor (but only one of them can be selected)
  • If final modifies a variable, the value of the variable can only be assigned a value once, that is, the constant public final static String SHI_YAN_LOU="shiyanlou";

Permission modifier

encapsulation

  • Data can only be accessed through specified methods.
  • Hide the instance details of the class to facilitate modification and implementation.
  1. Modify the visibility of the attribute and add a modifier (private) in front of the attribute
  2. Provide external public method access for each value attribute, such as public, such as creating getter/setter (value and assignment) methods for accessing private attributes
  3. Add the control statement of the attribute in the getter/setter method. For example, we can add a judgment statement to deny illegal input.

public class People {
    //Property (member variable). The access modifier private has been added in front of it
    //Becomes a private property and must be called through a method
    private double height;     //height

    //The attribute has been encapsulated. If the user needs to call the attribute
    //Must be called with getter and setter methods
    //getter and setter methods need to be defined by programmers themselves
    public double getHeight(){
    //The getter method name is the get keyword plus the attribute name (the initial letter of the attribute name is capitalized)
    //The getter method is generally used to get the attribute value
      return height;
    }

    //Similarly, set our setter method
    //The setter method name is set keyword plus attribute name (initial capital)
    //setter method usually assigns a value to the attribute value, so it has a parameter
    public void setHeight(double newHeight){
      height = newHeight;
    }
}

public class NewObject {

    public static void main(String[] args) {
        People LiLei = new People();    //Created a People object, LiLei

        //Assign values to attributes using setter methods
        LiLei.setHeight(170.0);

        //Get the attribute value by getter method
        System.out.println("LiLei What's your height"+LiLei.getHeight());
    }
}


this

This keyword represents the current object. Use this Property operates the property of the current object, this Method calls the method of the current object.

Attributes decorated with private can only be accessed by defining getter and setter methods (ides such as Eclipse and IDEA have the function of automatically generating getter and setter methods).

public void setAge(int age) {
  this.age = age;
}
public int getAge() {
  return age;
}

inherit

For code reuse

class Subclass extends Parent class
class Dog extends Animal {
    ...
}
  • The subclass has all the properties and methods of the parent class except private.
  • Subclasses can have their own properties and methods.
  • Subclasses can override methods that implement the parent class.
  • Inheritance in Java is single inheritance. A class has only one parent class.

Note: one way to implement multi inheritance in Java is to implement the interface, but the interface cannot have non static attributes. Please note this.

super

The super keyword is used inside the subclass to represent the parent object.

  • Access the property super of the parent class Property name.
  • Access the superclass method bark().
  • When the subclass constructor needs to call the constructor of the parent class, the top position in the constructor body of the subclass: super().

Overloading and rewriting

Method overloading refers to defining multiple methods with the same name in a class, but each method is required to have different parameter types or the number of parameters. Method overloading is generally used to create a set of methods with similar tasks but different parameters.

  • The parameter list in the method must be different. For example, the number of parameters is different or the type of parameters is different.
  • Different exceptions are allowed in overloaded methods
  • There can be different return value types, but the parameter list must be different.
  • There can be different access modifiers.
public class Test {
    void f(int i) {
        System.out.println("i=" + i);
    }

    void f(float f) {
        System.out.println("f=" + f);
    }

    void f(String s) {
        System.out.println("s=" + s);
    }

    void f(String s1, String s2){
        System.out.println("s1+s2="+(s1+s2));
    }

    void f(String s, int i){
        System.out.println("s="+s+",i="+i);
    }

    public static void main(String[] args) {
        Test test = new Test();
        test.f(3456);
        test.f(34.56f);
        test.f("abc");
        test.f("abc","def");
        test.f("abc",3456);
    }
}

Method Rewriting: a subclass can inherit the methods of the parent class. However, if a subclass is not satisfied with the methods of the parent class and wants to add some operations suitable for itself, it needs to rewrite the methods. And in the calling method of subclass, the method of subclass shall be called first.

Of course, when rewriting a method, you should pay attention to that the rewritten method must be consistent with the method syntax of the original parent class, such as the return value type, parameter type and number, and method name.


public class Animal {
    //Class method
    public void bark() {
        System.out.println("Animals call!");
    }
}




public class Dog extends Animal {
       //Override the bark method of the parent class
        public void bark() {
        System.out.println("Woof! Woof! Woof!");
    }
}




public class Test{
    public static void main(String args[]){
           Animal a = new Animal(); // Animal object
        Dog d = new Dog();   // Dog object

          Animal b = new Dog(); // Dog object is transformed upward into Animal type, which will be explained in detail later

          a.bark();// Execute the method of the Animal class
         d.bark();//Method of executing Dog class
          b.bark();//Method of executing Dog class
       }
}


polymorphic

Polymorphism means that different kinds of objects are allowed to respond to the same message. That is, the same message can adopt many different behavior modes according to different sending objects. Polymorphism, also known as dynamic binding, refers to judging the actual type of the referenced object during execution and calling its corresponding methods according to its actual type.

  • Implementation conditions of polymorphism
    There are three necessary conditions for Java to realize polymorphism:
  1. Inheritance
  2. rewrite
  3. Upward transformation (that is, the parent class reference points to the child class object).
Animal a = new Animal();  //a is the reference of the parent class and points to the object of this class

Animal b = new Dog(); //b is the reference of the parent class and points to the object of the child class



  • Implementation of polymorphism
    The implementation of polymorphism in Java: inherit the parent class for method rewriting, abstract classes and abstract methods, and interface implementation.

Upward transformation

class Animal {
    //Parent method
    public void bark() {
        System.out.println("Animals call!");
    }
}

class Dog extends Animal {

    //The subclass overrides the bark method of the parent class
    public void bark() {
        System.out.println("Woof, woof, woof!");
    }
    //Subclass own method
    public void dogType() {
        System.out.println("What kind of dog is this?");
    }
}


public class Test {

    public static void main(String[] args) {
        Animal a = new Animal();
        Animal b = new Dog();
        Dog d = new Dog();

        a.bark();
        b.bark();
        //b.dogType();
        //b.dogType() compilation failed
        d.bark();
        d.dogType();
    }

}
$ javac Test.java
$ java Test
 Call animals!
Woof, woof, woof!
Woof, woof, woof!
What kind of dog is this?

Here, since b is the reference of the parent class and points to the object of the child class, the method of the child class (dogType() method) cannot be obtained. At the same time, when the bark() method is called, the bark() method in the child class is called because the child class overrides the bark() method of the parent class.

Therefore, during the upward transformation, the different methods in the subclass object and the parent object will be forgotten, and the same method in the parent class - override (method name and parameters are the same) will be overwritten.

abstract class

There are abstract methods in abstract classes. This method is incomplete. It has only declarations and no method body. Abstract method declaration syntax is as follows:
abstract void f(); // The f () method is an abstract method

In some cases, a parent class only knows what methods its subclasses should contain, but it cannot know exactly how these subclasses implement these methods. That is to say, an abstract class restricts which methods must be implemented by subclasses, and does not pay attention to how the methods are implemented.
An abstract class is abstracted from multiple classes with the same characteristics, and this abstract class is used as the template of the subclass, so as to avoid the randomness of subclass design.

How can an abstract class be implemented in code? Its rules are as follows:

  • Define abstract classes with the abstract modifier.
  • Abstract modifier is used to define abstract methods, which only needs declaration and no implementation.
  • A class that contains abstract methods is an abstract class.
  • Abstract classes can contain ordinary methods or no abstract methods.
  • The object of an abstract class cannot be created directly. It is usually defined that the reference variable points to the subclass object.
//Abstract method
public abstract class TelePhone {
    public abstract void call();  //Abstract method, call
    public abstract void message(); //Abstract methods, texting
}

public class CellPhone extends TelePhone {

    @Override
    public void call() {
        System.out.println("I can call!");
    }

    @Override
    public void message() {
        System.out.println("I can text!");
    }

    public static void main(String[] args) {
        CellPhone cp = new CellPhone();
        cp.call();
        cp.message();
    }

}


Interface

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


// Animal.java
interface Animal {
        //int x;
        //Compilation error. x needs to be initialized because it is of static final type
        int y = 5;
        public void eat();
        public void travel();
}

// Cat.java
public class Cat implements Animal{

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

     public void travel(){
         System.out.println("Cat travels");
     }
     public static void main(String[] args) {
        Cat cat = new Cat();
        cat.eat();
        cat.travel();
    }
}

In Java 8:

  • Interfaces cannot be used to instantiate objects.
  • Methods in the interface can only be abstract methods, default methods and static methods.
  • The interface member is of type static final.
  • The interface supports multiple inheritance.

Inner class

Putting the definition of one class inside the definition of another class is called inner class.

The main functions of internal classes are as follows:

  • The inner class provides better encapsulation. You can hide the inner class in the outer class and do not allow other classes in the same package to access this class
  • Methods of internal classes can directly access all data of external classes, including private data
  • The functions realized by the internal class can also be realized by using the external class, but sometimes it is more convenient to use the internal class
  • Internal classes allow you to inherit multiple non interface types (details will be explained later)

Note: internal class is a compile time concept. Once compiled successfully, it will become two completely different classes. For an external class named outer and its internally defined internal class named inner. After compilation, outer Class and outer $inner There are two classes. Therefore, the member variable / method name of the inner class can be the same as that of the outer class.

// People.java
//External class People
public class People {
    private String name = "LiLei";         //Private properties of external classes
    //Internal class Student
    public class Student {
        String ID = "20151234";               //Member properties of inner classes
        //Methods of inner classes
        public void stuInfo(){
            System.out.println("Access the in an external class name: " + name);
            System.out.println("Access the in the inner class ID: " + ID);
        }
    }

    //Test member inner class
    public static void main(String[] args) {
        People a = new People();     //Create an external class object named a
        Student b = a.new Student(); //Use an external class object to create an internal class object named b
        // Or people Student b = a.new Student();
        b.stuInfo();   //Call suInfo method of internal object
    }
}

  • The Student class is equivalent to a member variable of the People class, so the Student class can use any access modifier.
  • The Student class is in the People class, so all methods within the access scope of the class can access the properties of People (that is, the internal class can directly access the methods and properties of the external class, and vice versa).
  • After defining the member's internal class, you must use the external class object to create the internal class object, that is, the internal class object name = external class object new inner class ();.
  • If the external class and the internal class have the same member variables or methods, the internal class accesses its own member variables or methods by default. If you want to access the member variables of the external class, you can use the this keyword. As in the above code: a.this.
// People.java
//External class People
public class People {
    private String name = "LiLei";         //Private properties of external classes

/*Static variables of external classes.
Java Members modified by static in are called static members or class members. It belongs to the whole class, not to an object, that is, it is shared by all objects of the class. Static members can be accessed directly by class name or by object name.
*/
    static String ID = "510xxx199X0724XXXX";

    //Static inner class Student
    public static class Student {
        String ID = "20151234";               //Member properties of inner classes
        //Methods of inner classes
        public void stuInfo(){
            System.out.println("Access the in an external class name: " + (new People().name));
            System.out.println("Access the in an external class ID: " + People.ID);
            System.out.println("Access the in the inner class ID: " + ID);
        }
    }

    //Test member inner class
    public static void main(String[] args) {
        Student b = new Student();   //Directly create an internal class object named b
        b.stuInfo();                 //Call suInfo method of internal object
    }
}

Static inner classes cannot directly access non static members of external classes, but they can use new outer class () Member access.
If the static member of the external class has the same name as the member of the internal class, you can use the class name Static members access static members of external classes; If the static member of the external class and the member name of the internal class are different, the static member of the external class can be called directly through the member name.
When creating an object of a static internal class, you do not need an object of an external class. You can directly create an internal class object name = new internal class();.

Local inner class

// People.java
//External class People
public class People {
    //Within a method defined in an external class:
    public void peopleInfo() {
        final String sex = "man";  //Constants in external class methods
        class Student {
            String ID = "20151234"; //Constants in Inner Classes
            public void print() {
                System.out.println("Constants in methods that access external classes sex: " + sex);
                System.out.println("Accessing variables in internal classes ID:" + ID);
            }
        }
        Student a = new Student();  //Create an object of a class inside a method
        a.print();//Call the method of the inner class
    }
    //Within the scope defined in the external class
    public void peopleInfo2(boolean b) {
        if(b){
            final String sex = "man";  //Constants in external class methods
            class Student {
                String ID = "20151234"; //Constants in Inner Classes
                public void print() {
                    System.out.println("Constants in methods that access external classes sex: " + sex);
                    System.out.println("Accessing variables in internal classes ID:" + ID);
                }
            }
            Student a = new Student();  //Create an object of a class inside a method
            a.print();//Call the method of the inner class
        }
    }
    //Test method inner class
    public static void main(String[] args) {
        People b = new People(); //Create an object of an external class
        System.out.println("Defined within the method:===========");
        b.peopleInfo();  //Calling methods of external classes
        System.out.println("Defined in scope:===========");
        b.peopleInfo2(true);
    }
}

Anonymous Inner Class

Anonymous inner class, as the name suggests, is an inner class without a name. Because there is no name, anonymous inner classes can only be used once. It is usually used to simplify code writing. But there is another prerequisite for using anonymous inner classes: you must inherit a parent class or implement an interface.

// Outer.java
public class Outer {

    public Inner getInner(final String name, String city) {
        return new Inner() {
            private String nameStr = name;
            public String getName() {
                return nameStr;
            }
        };
    }

    public static void main(String[] args) {
        Outer outer = new Outer();
        Inner inner = outer.getInner("Inner", "NewYork");
        System.out.println(inner.getName());
    }
}
interface Inner {
    String getName();
}

Inner

package

Organize similar or related classes or interfaces in the same package to facilitate the search and use of classes.
The package adopts the storage mode of 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.
Packages also limit access rights. Only classes with package access rights can access classes in a package.

The naming convention for packages is all lowercase spelling.

Tags: Java

Posted by eduinfo on Thu, 12 May 2022 17:32:36 +0300