Object-oriented features

Posted by spiyun on Tue, 14 May 2019 17:29:44 +0200

Article Directory

CHAPTER IX OBJECT-ORIENTED CHARACTERISTICS

1. Encapsulation - Privatization of Member Variables

Encapsulation Meaning: Hide, hide implementation details, and provide only a uniform interface for external calls
[Encapsulation Purpose]: (1) Protect the security of data (2) Facilitate caller invocation

Privatization of member variables is a good encapsulation

  1. [Ways to Privateize Members]
    Decorate member variables with private permissions.
  2. [Effect of member privatization]
    Privateized members can only be accessed inside a class and not outside a class
  3. [Want access to private members]
    Need to provide a uniform interface to the outside world (providing uniform public privileges get or set assignments)

Shortcut keys in eclipse generate get and set shift+alt+s right-click source

  • Class Association: Class A is set to the property of B - the method of A can be called under Class B

  • Inherited Class B inherits Class A --- A method can be called under Class B

    Inheritance: The parent-child inheritance relationship between general and special.
    Designed as inheritance.Reduce code redundancy
    Design angle, subclass before parent class
    Class of association: There is no direct relationship at all.
    Why?

class Person2{
	public String name="Zhang San";
	private int age1=100;
	public void test(){
		System.out.println(this.name);
		System.out.println(this.age1);
	}
	public String getAgeStr(){
		return "[Age]: "+this.age1;
	}
	public int getAge(){
		return this.age1;
	}
	public void setAge(int age){
		this.age1=age;
	}
}
public class Day6_4_OOP {
  public static void main(String[] args) {
	  Person2 p=new Person2();
	  System.out.println("Full name:"+p.name);
	  p.name="Li Si";
//	  System.out.println(p.age);
	  System.out.println(p.getAgeStr());
	  System.out.println(p.getAge());
	  p.setAge(40);
	  System.out.println(p.getAge());
	   
  }
}

2. Inheritance

2.1 Background

[Background]: Create two Java Teacher Python Teachers after requirement analysis
Attributes and Behaviors
Java Teacher: Name, Age, Self-introduction, Lecture
Python Teacher: name, age, self-introduction, lecture
PhpTeaher

2.2 Implementation

Inheritance implements general and special relationships.
General: parent class
Special: subclasses (extension classes, derived classes)

The effect of inheritance: subclasses will have members under the parent, and subclasses can be implemented separately if they need more advanced functionality.
(1) Type of inheritance

  • Implicit Inheritance: When a class does not explicitly inherit any class, each java class inherits Object by default
    About Object Class Later Lecture

  • Explicit inheritance:
    Syntax: When defining a class, use the child class name extends parent class name
    A class in java can inherit only one parent (single inheritance) and can inherit from a son to a father at multiple levels, and from a father to an ancestor.
    Fruit (father) and apple (son)

Important operator instanceof
Keyword

  • Usage: Determine if the object is generated by a class (parent)?
  • Syntax: object instanceof type (parent)
  • [Use occasions] Middle school pupils, primary school students and college students can pay half the price if they are students
 s Student Object
 if (s instanceof middle school || s instanceof primary school || s instanceof College students)
Student's Parent
 if (s instanceof Student)
class Fruit{
	public void show(){
		System.out.println("Fruits");
	}
}
class Apple extends  Fruit{
	
}
public class Day6_4_OOP{
	public static void main(String[] args) {
		Apple a=new Apple();
		Fruit f=new Fruit();
//		a.show();
		System.out.println(a instanceof Apple);
		System.out.println(a instanceof Fruit);
		System.out.println(a instanceof Object);
	}
}

Inheritance of 2.3 Members

[Conclusion]
When the child and parent are in the same package, the child can inherit the parent public protected and default
When the child and parent are no longer in the same package, the child can inherit the parent public protected
But in no case can private be inherited
protected member, if the class is in the same package, the subclass can inherit to the parent member.
If you declare a public class subclass in a different package, you can access the protected member under the parent class

pulic class  Fruit{
	private int privatAttr;
	protected int protectedAttr;
	public int publicAttr;
	int defaultAttr;
}
public class Apple extends Fruit{
	
}

public class Day6_4_OOP{
	public static void main(String[] args) {
		Apple a=new Apple();
		System.out.println(a.publicAttr);Not accessible
		System.out.println(a.protectedAttr);
		System.out.println(a.defaultAttr);
	}
}

Extension of 2.4 Subclass

2.5 Rewrite

If the subclass considers the method under the parent unavailable, inadequate, and inappropriate, it can implement the method itself - override (override) the method under the parent
[Rewrite Effect]
When a method under a subclass is invoked, if there is an override, the subclass method is invoked, if there is no override, the method under the parent is invoked
[Override]: Define the same method as the parent class (method name, parameters, return values are identical to the parent class) (return values and parameters can also be generic type erasable types)

[Rewrite Rules]
(1) Define the same method as the parent (method name, parameters, return values are identical to the parent)
(2) Require subclass methods to have no lower permissions than parent methods (the same may) - to extend methods and attributes of the parent class
(3) Generics of parameter types and return values (later)
(4) Subclasses cannot throw more exceptions than parent methods (later)

[Rewrite Tag (Understanding)]@Override: In order to mark rewrite, it is assumed that in some cases, the method is not overridden, but it does not make a mistake. To satisfy the rewrite requirement, a tag can be added to indicate whether the subclass has successfully rewritten.

[Override]: Create a method under a subclass that has the same method name, parameters, and return values as the parent class.

  • Method name: Same.
  • Parameter: Same, generic erasable type after 1.5
  • Return value: Same, after 1.5, the child type of the return parent class can also be.
    (1)void
    (2) are basic data types, int-int
    (3) Parent method returns Fruit subclass method can also return Fruit, or Apple - alternative type
  • [Role] If a subclass does not override its parent's methods, it calls methods under the parent class, and if it overrides its methods, it calls its own methods.
    It is the basis of the manifestation of polymorphism.
class Fruit{
	String name="initial value";
	public void setName(){
		this.name="aaa";
	}
	public void show(){
		System.out.println("Fruits");
	}
}
class Apple extends Fruit{
	
//	public void show(){
//		System.out.println("I'm an apple");
//	}
//	@Override
	public void show(int a,int b){
		
	}
	public void newfun(){
		System.out.println("Special methods under subclasses");
	}
}

public class Day6_4_OOP{
	public static void main(String[] args) {
		Apple a=new Apple();
		Fruit f=new Fruit();
		a.show();
		a.newfun();
		f.show();
//		f.newfun();
		a.setName();
		System.out.println(a.name);
		System.out.println(f.name);
	}
}

Hide of 2.6 Member Variables

Attributes -- "Rewrite" --- are not really overrides in nature, they are just hidden.
If a member variable is declared in the parent class, a member variable with the same name is also declared in the subclass. When a subclass object is called, members of the subclass hide members of the parent class
As long as the names are the same, they are hidden, regardless of the type.
Don't design like this.

    class Fruit{
        public int aaa=0;
    }
    class Apple extends Fruit{
        public String aaa="hello";
    }

    public class Day7_1_OOP {
    public static void main(String[] args) {
        Apple a=new Apple();
        System.out.println(a.aaa);
    }
    }

2.7 Inheritance of Constructors

(1) Constructors in Inheritance

[Principles]
The constructor is not a member of the class, so it cannot be inherited, but it can call the constructor of the parent class.
Calling the use of a parent constructor requires the super keyword, which must be placed on the first line of the subclass constructor
When subclass objects are created, [must] run the parent class's constructor first.(in other words, an anonymous parent object must be created)
First, if there is no constructor defined in the subclass, or if there is no explicit call to other parameterized constructors of the parent class in the subclass constructor, the subclass object must be created
The parameterless constructor of the parent class is invoked, then its own constructor is invoked.
Second, if the super parent class in a subclass has a parameterized constructor, the parameterized constructor of the parent class will be invoked first when the subclass object is created.Then call your own constructor.
What happens when a child class does not have an explicit constructor that calls the parent class in the constructor and the parent class only has a parameterized constructor?Errors will occur
[Think] Must run the parent class's constructor first?Why?
Reason: When creating subclass objects, you need to create members inside. Some members are under the parent class. Only if you have a parent object, you can find the members of the parent class.
So the bottom level of java requires that parent objects be created first.
When all classes produce objects, they actually create a class of Objects. (Object's constructor)

[super requires on the first line]: In order to call the parent class's constructor before initializing its own content, otherwise the parent constructor's content will overwrite the contents of the child class.

    class Fruit{
        public Fruit(){
            System.out.println("Parent Class Fruit Parameterless constructor");
        }
        public Fruit(String name){
            System.out.println("Parent Class Fruit A parameterized constructor");
        }
        public void show(){
        }
    }
    class Apple extends Fruit{
        public Apple(){
            super();//If there is no explicit constructor in the subclass that calls the parent class, it is equivalent to adding this sentence to the subclass constructor
            super("hello");
            System.out.println("Subclass Apple Parameterless constructor");
        }
    }

    public class Day7_1_OOP {
        public static void main(String[] args) {
            Apple a=new Apple("Red Fuji");
            //The show method should be created under the Apple object.
        }
    }

(2) About the super keyword

super is a reference to the parent class (the name of the parent object) in a class that inherits a relationship
Role: First: Place in the subclass constructor, on the first line, to call the parent constructor
Second: super.member variable name: refer to the member variable of the parent class in the subclass (accessible, modifiable (note permissions))
Third: super.Method name: A method that can be used to reference a parent class in a subclass.
[Real application] In setting private members of the parent class

    class Fruit{
        public String name="Fruits";
        private int age;
        
        public Fruit(){
            System.out.println("Parent Class Fruit Parameterless constructor");
        }
        public void show(){
            System.out.println("Parent class show Method");
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
    }
    class Apple extends Fruit{
        public Apple(){
            super();//If there is no explicit constructor in the subclass that calls the parent class, it is equivalent to adding this sentence to the subclass constructor
            super("hello");
            System.out.println("Subclass Apple Parameterless constructor");
            System.out.println(super.name);//Call properties of parent class
            System.out.println(super.age);
            super.setAge(10);
        }
        public void test(){
            super.show();
        }
    }

    public class Day7_1_OOP {
        public static void main(String[] args) {
            Apple a=new Apple();
            Apple Should be created under object show Method.
            a.test();
        }
    }

(3) Implement background references by inheritance

  • Java Teacher: Name, Age, Self-introduction, Lecture
  • Python Teacher: name, age, self-introduction, lecture
    Idea: Extract the common attributes name and age introducer and teach of the parent Teacher

2.8.final keyword

Background: A class thinks it's well designed and doesn't want to be extended (it doesn't want subclasses)
final

  1. Attributes and layout variables can be modified, but none of them can be repaired.

  2. Modified methods may be modified, and modified methods may not be overridden

  3. Modified classes can be modified, and modified classes cannot be inherited
    A class declares a final type, and all methods below it are considered final methods.

    [Usage]
    (1)final modifier variables (member variables, local variables)

    None of the modified variables can be modified

    First: Modify member variables
    Member variables need to be initialized, and once initialized, they cannot be changed.
    How to initialize: You can initialize at the same time you declare it, or you can initialize it in the constructor, whichever you choose.
    The purpose is to determine the value of a final type variable before the object is created.
    Second: Modify local variables
    It can be a formal parameter, a local variable declared in a method.

    Static is modifiable, a member of a static declaration that is shared by multiple objects and is only related to a class, not not unavailable
    final is truly unmodifiable.
    When static s and final s were used to declare a constant, the constant could only be assigned at the same time it was declared.
    (Because members of static s are only related to classes, not objects, and constructors are designed to construct objects.)

    class Apple{
        private final String name="aaa";
        private final String name;
        private static final int V=123;
        public Apple(){
            this.name="bbb";
            System.out.println(this.name);
        }
        public void show(final int age){
            ///When the show method is called, the formal parameter must be bound to the actual parameter and assigned a value at the same time.
            //The assignment below becomes a modification
            age=10;
            final String type="hello";
            type="new"; finalLocal variables cannot be modified again
        }
    }

(2)final modification method
[Rule] Method modified with final cannot be overridden

    class Fruit{
        public final void show(){
            
        }
    }
    class Apple extends Fruit{
        public final void show(){Cannot be overridden
            
        }
    }

(3) A final modifier class cannot be inherited
Modifier classes cannot be inherited, and all parent class methods are considered final type methods

final class Fruit{
    public  void show(){
        
    }
}
class Apple extends Fruit{
    public  void show(){
        
    }
}

2.9. Conversion between reference types

Between reference types, if there is no relationship between reference types that can not be converted at all (including implicit and mandatory conversion)
If there are classes inherited from parent-child relationships
[Conclusion]
Parent-type objects assigned to child-class types (high->low) can undergo coercion (but conditionally)
Subclass objects are assigned to parent types (low->high), which can be implicitly converted.

    class Fruit{
    }
    class Apple extends Fruit{
    }
    public class Day7_1_OOP {
        public static void main(String[] args) {
            Fruit f=new Fruit();
            Apple a=new Apple();          
            //Cannot convert between types without any relationship
            String s=(String)f;
            String s="hell";
            Fruit f=(Fruit)s;
            f=a;//Because of this assignment, the object a points to is given to f, and the address a stores to the address f stored in F really becomes a subclass object
            a=(Apple)f;
            Apple a2=(Apple)f;
            Fruit f2=a;
        }
    }

[Parent reference to child class object] (very useful)
Since f=a can use a parent reference f to catch a child object a
Can you create a parent class reference directly and assign values to it using a subclass object?
[Parent Reference Points to Subclass Object] Result:
If the method under this object is called, and if it is overridden in a subclass, the method after override is called.
If there is no override in the subclass, the method under the parent class is called.

[Parent Reference Points to Subclass Object]: A parent type object is created using subclasses
Upward Styling: Up (Parent): Hardens the child object into the parent type - [Parent Reference Points to Child Object]
Downward Styling: Down (Child): Harden parent objects into subclass types (conditional, need to convert objects into subclass objects ahead of time)

    class Fruit{
        public void show(){
            System.out.println("Fruitful show");
        }
    }
    class Apple extends Fruit{
        public void show(){
            System.out.println("Apple show");
        }
        public void j(){
            System.out.println("Apple sauce");
        }
    }
    public class Day7_1_OOP {
        public static void main(String[] args) {
            [Parent Reference to Subclass Object (Very Useful)
            Fruit f=new Apple();
            f.show();
            Apple a =new Fruit();No: If Apple There are methods or attributes that the parent class does not have. a.Special methods.
        }
    }

3. Polymorphism

The meaning of polymorphism: is an external form of expression, with a variety of specific implementations.
Specific manifestations of polymorphism in java:
(1) Method overload: The method name is one, but the functions implemented are different.
(2) Method override: The method in the parent class is the same as the method in the child class, but it implements different functions.
(3) Polymorphic parameters

  1. Parent Reference Points to Subclass Object
    If java needs to be executed, it will take two periods, one is compilation and the other is runtime
    T = new T() when creating a reference type;
    =Partial compilation time on the left: specify the type to be created (to make room)
    =Partial runtime on the right: the object you really want to create.
    When an object appears in the program and the properties or methods under the object are called:
    [t.attrfun]
    The program will determine the period, and call different content depending on the period in which the attributes or methods in the object originate.
    Compile-time generation: Whether the attrfun name can be called at compile-time arrives, and whether it matches the compile-time type.
    Runtime generation: Whether the attrfun name can be called at runtime arrives, and whether it meets the type of runtime.
    (1) The type of run-time and compile-time is the same.
    A a=new A();
    When A is declared, if type A is declared, the compilation time is type A, and when attributes or methods are accessed, whether the content declared in the compilation time type is satisfied
    a.show(); detects if the show method exists in A.
    When a real object is created, the constructor executed, executed at runtime, and when a property or method is accessed, it detects the existence of the property or method in the runtime type.
    Content generated at compile time: attributes (static and non-static), static members
    What happens during runtime: methods, constructors, instance blocks

    (2) Different types of run-time and compile-time (parent references point to subclass objects)
    Father f=new Son();
    Follow the above theory
    When we access attributes, static methods, we go to the Father class to verify validity.
    When we access methods, constructors, and instance blocks, we go to the Son class to verify validity and execute what's in Son.

  2. Calls to validate members
    Block, static member, instance member
    When creating parent class references to subclass objects:
    [Conclusion]
    If a parent reference points to a subclass object:
    When a related member of a subclass object is called:
    If it is a property, static member: the property and static member of the parent class are invoked.
    If it is a method, constructor: the method or constructor to the subclass is called.

(1) Static and instance blocks: all executed

    class Fruit{
        static{
            System.out.println("Static block under Parent");
        }
        {
            System.out.println("Instance block under parent class");
        }
    }
    class Apple extends Fruit{
        static{
            System.out.println("Static block under subclass");
        }
        {
            System.out.println("Instance block under subclass");
        }
    }


    public class Day7_1_OOP {
        public static void main(String[] args) {
            Fruit f=new Apple();When a subclass constructor is called, it must call the constructor of the parent class
        }
    }

(2) Calls to non-static methods (commonly used)

class Fruit{
    public void show(){
        System.out.println("Under Parent show");
    }
}
class Apple extends Fruit{
    public void show(){
        System.out.println("Subclass show");
    }
    public void j(){
        System.out.println("Subclass j Method (not in parent)");
    }
}

public class Day7_1_OOP {
    public static void main(String[] args) {
        Fruit f=new Apple();
        f.j();Compilation failed
        f.show();Methods are created at runtime and, when executed, methods under runtime objects are executed.
    }
}

(3) Calls to static methods

    class Fruit{
        public static void show(){
            System.out.println("Under Parent show");
        }
    }
    class Apple extends Fruit{
        public static void show(){
            System.out.println("Subclass show");
        }
    }

    public class Day7_1_OOP {
        public static void main(String[] args) {
            Fruit f=new Apple();
            f.show();Because static methods are generated at compile time, they are executed under the parent type
        }
}

(4) Member variables
For attributes, even if there are attributes under a subclass that override the parent class, the attributes of the parent class are also accessed when the parent reference points to the subclass object.
This is because attributes are generated at compile time.

    class Fruit{
        public String name="Fruits";
        public void setApple(){
        }
    }
    class Apple extends Fruit{
        public String name="Apple";
        public String name;
        public Apple(){
            this.name="Apple";
        }
        public void setApple(){
            this.name="Apple";
            System.out.println(this.name);
        }
    }
    public class Day7_1_OOP {
        public static void main(String[] args) {
            Fruit f=new Apple();
            f.setApple();
            System.out.println(f.name);Always access properties under the parent class (compile-time type)
        }
    }

For methods: there is an override
For attributes: hidden (for "overrides" of attributes - not overrides in nature, but hides)
Whether polymorphism can be achieved in java is an essential difference between rewriting and hiding.
Rewrite implements polymorphism and determines which member to call based on the true type of the runtime object.
Hide can't implement polymorphism, always execute compile-time properties
/

3. Polymorphic parameters
Use [indirect] for parent references to subclass objects
Below the Java Teacher Python Teacher are the teach methods
Background: Requirements, expect the Test class, Java Teacher Python Teacher, to implement references between classes through dependencies.
For example, Test has a record method with Teacher as a formal parameter
What if you want to call the teach method under Java and python Teachers in record?

    class PyhtonTeacher{
        public void teach(){
            System.out.println("python Attend class;class begins");
        }
    }
    class JavaTeacher{
        public void teach(){
            System.out.println("java Attend class;class begins");
        }
    }
    public class Day7_1_OOP {
        public void record(PyhtonTeacher pt,JavaTeacher jt){
            //You want to call the teach method under PyhtonTeacher JavaTeacher.
            pt.teach();
            jt.teach();
        }
        public void record(PyhtonTeacher pt){
            pt.teach();
        }
        public void record(JavaTeacher jt){
            jt.teach();
        }

        public static void main(String[] args) {

        }
    }

[Definition of polymorphic parameters]: Formal parameters are defined as the type of a parent class. Methods in the parent class are overridden in each subclass. When a method is called,
The method under which subclass object the actual parameter passes in will be called.
This form of parameter is called a polymorphic parameter
Actual parameters assign values to formal parameters:
The variable name binds to the same variable name.
T t=new T();
T t2=t;
Establishment of polymorphic remodeling: inheritance, override (override)

    class Teacher{
        public void teach(){
        }
    }
    class PyhtonTeacher extends Teacher{
        public void teach(){
            System.out.println("python Attend class;class begins");
        }
    }
    class JavaTeacher extends Teacher{
        public void teach(){
            System.out.println("java Attend class;class begins");
        }
    }
    public class Day7_1_OOP {
        public void record(Teacher t){
            //Equivalent to experiencing a Teacher t=pt;    Parent Reference  t=Subclass object
            t.teach(); Calls to methods under subclass objects
        }
        public static void main(String[] args) {
            Day7_1_OOP test=new Day7_1_OOP();
            PyhtonTeacher pt=new PyhtonTeacher();
            JavaTeacher jt=new JavaTeacher();
            test.record(pt);
            test.record(jt);
        }
    }

Topics: Programming Java Python Eclipse