"Java Learning Notes" object-oriented

Source: Internet
Author: User
Tags ticket

    • The development of programming language
    • Process-oriented design ideas
    • Object-oriented design idea
    • Concepts of objects and classes
    • The relationships between classes
    • Objects and references
    • Definition of Java class
    • constructor function
    • Creation and use of objects
    • this keyword
    • Static keyword
    • Package and Import statements
    • Access control
    • Inheritance of Classes
    • Override of Method
    • Final keyword
    • Object class
    • Object transformation
    • Polymorphic
    • Abstract class
    • Interface
The development of programming language
    • Machine language
    • Assembly
    • High-level language – process-oriented language
    • Object-oriented language
Process-oriented thinking and object-oriented design

Object-oriented thinking:

    • The appropriate method appears in the appropriate class

In the problem domain, you no longer consider the step-by-step process, but rather abstract the objects in the problem domain and clarify the relationship between objects and objects.

Focus: Three steps for object-oriented implementation:

    1. What classes of objects are in the question.
    2. These classes have properties and methods for these objects.
    3. What are the relationships between classes and classes: Association (weak), inheritance (strong), aggregation (strong), implementation (between parent class and subclass), polymorphism.
Concepts of objects and classes
    • Class: An abstraction of a class of things, including static attributes (member variables) and dynamic properties (methods). Bottle
    • Object: A specific instance of a class of transactions. "Some bottle."

the relationship between classes (objects)

    • Association relationship

      Association relationship: A method of a class that is associated with an object of a class.

    • Inheritance relationships (general and special)

      Easy to form an inheritance tree

      XX is a kind of XX: Ball player is a kind of athlete.

      A class can inherit from several different classes. "Multiple Inheritance: C + +"

    • Aggregation relationships (whole and part)

      Aggregation: Loose coupling

      Combination: Essential

    • Implementing relationships

      The parent class's method, subclass to implement.

    • Polymorphic


Categories: Travel agencies, passengers, air tickets, accounts

Properties: Shift
Method: Send Ticket, void, show flight time

Java and object-oriented

Classes must be defined before they can have objects

    • object is the core of a Java program, in a Java program "Everything is Object".
    • objects can be considered as packages of static properties (member variables) and dynamic properties (methods).
    • A class is a template that is used to create the same class of objects, and defines the member variables and methods that such objects should have in a class.
    • J2SDK itself provides many classes for programmers to use, and programmers can define their own classes.

Why use objects?

Definition of Java class

Convention Naming conventions:

    • Capitalize the first letter of the class name
    • The first letter of the variable name and method name is lowercase
    • Use hump marking
//define a class with the class keyword, for example:  class person{//member variable definition  private  int  ID; private     int  age = 20 ;    //method definition  public  int  getage     () {return  age; } public  void  setAge     (int  i) {age = i; } public  int  getId     () {return  ID; }}

Member variables

    • Member variables can make any one of the data types in the Java language, including basic types and reference types.

    • When a member variable is defined, it can be initialized or not initialized, and Java gives the default initialization value when it is not initialized.

    • Member variables are scoped to the entire class body.


Variable types other than the base types in Java are referred to as reference types.

Objects in Java are manipulated by reference.

    • Base type: Occupies a piece of memory.
    • Reference type: Two memory (a small chunk of memory points to a chunk of memory). (stack) + Real objects (stored in heap memory)

Relationship of classes and objects

Constructor Method (constructor)
  • Create a new object using the new+ construction method.
  • A constructor is a function that is defined in a Java class to initialize an object.
  • The
  • Constructor has the same name as the class and no return value.

    public      Class  person{int  ID;    int  age;            Person (int  n,int  i) {id = n; age = i;}}  
  • When you create an object, you use the constructor to initialize the member variables of the object.

    publicclass Test{    publicstaticvoidmain(String args[]){            new Person(1,25);            new Person(2,27);}}

  • When no constructor is specified, the compiler automatically adds a constructor for the class, such as: class name () {} .

    class Point{   public int x;   public int y;    }... Point p = new Point();

Method overloading
  • Overloading of the
  • method refers to multiple methods in a class that can be defined with the same name, but with different parameters. When called, the corresponding method is selected according to the different parameter tables.

    void  info () {System.out . println ( "my id is:"  + ID);} void  info (String t) {system.. println (t +  + ID);}  
  • Construction methods can also be overloaded.

    Person() {    id100;    20;}Person(int _id) {    id = _id;    30;}Person(int _idint _age) {    id = _id;    age = _age;}
object creation and use
    • Object must be created with the New keyword
    • Use the object "reference. Member variable" to refer to the object's member variable
    • Methods that use the object "Reference. Method (parameter list)" To invoke an object
    • There are different member variable storage spaces for each object of the same class
    • Methods for sharing this class with each object of the same category
      • Non-static methods are called for each object
this keyword
  • The This keyword used in the method definition of a class represents the application of an object that uses the method
  • Use this when you must indicate who is currently using the method's object
  • Sometimes this can be used to handle the case of member variables and parameter names in a method
  • This can be viewed as a variable whose value is a reference to the current object

     public  class     leaf{int  i = 0 ;    Leaf (int  i) {this  i = i;}        Leaf increament () {i++; return     this ; } void  print () {System.    Out . println ( "i ="  +i);} public  static  void  main  (string[] args)        {Leaf leaf = new  Leaf (100 );    Leaf.increament (). Increament (). print (); }}
Static keyword
    • In a class, a member variable declared with static is a static member variable, which is a common variable for the class, initialized on first use, and only one copy of the static member variable for all objects of that class.
    • A static method is declared with static, and when the method is called, the object's reference is not passed to it, so non-static members are inaccessible in the static method.
      • Static methods are no longer called on an object, so non-static members cannot be accessed.
    • Static members can be accessed through object references or class names, which do not need to be instantiated.
Package and Import statements

To facilitate the management of numerous classes in large software systems, and to address the naming conflicts of classes, the Java ingestion Package mechanism provides multiple class namespaces for classes.

    • If you want to put a class in the package, the first sentence in this class source file
    • You must ensure that the class file is in the correct directory
    • This type of source code may have an impact
      • Delete or transfer to a different directory
    • Another class that wants to visit.
      • Write full Name
      • Introduced
        • *
        • Specific class name
        • Accessing classes in the same package does not need to be introduced
    • The parent directory of the topmost package of the class file must be located under Classpath
    • Executing a class requires writing the full-package name

Introduction to the main packages in J2SDK

    • Java.lang contains some of the core classes of the Java language, such as String, Math, Integer, System, and thread, to provide common functionality.
    • java.awt contains several classes that form the abstract window toolkits, which are used to build and manage the graphical user interface (GUI) of the application.
    • Java.applet contains some of the classes required for applets to be used.
    • The java.net contains classes that perform network-related operations.
    • The java.io contains classes that provide multiple input/output capabilities.
    • Java.util contains a number of utility classes, such as defining system attributes, practical functions related to date calendars.
  • The classes in the Java.lang package do not need to be introduced and can be used directly.
  • Make your own class into a jar package: JAR-CVF Xxx.jar *. *
Inheritance of Classes
  • Java uses the extends keyword to implement a class's inheritance mechanism, with the following syntax rules:

    <modifier> class <name>  ...  ... }
  • By inheritance, subclasses automatically have all the members (member variables and methods) of the base class (superclass).

  • Java only supports single inheritance and does not allow multiple inheritance:

      • A subclass can have only one base class, and a base class may derive multiple subclasses
    //Permissions control in Inheritance class Parent{    Private intN_private =1;intn_friendly =2;//Package permissions: Can be accessed within the same package    protected intn_protected =3; Public intN_public =4;} class  child extends Parent {      Public voidF () {//n_private = 10; error, private variable in inheritance cannot be accessedn_friently = -; n_protected = -; N_public = +; }}
Access control
    • The Java permission modifier public protected private is placed before the member definition of a class to qualify other objects for access to members of that class of objects.

    • Permission adornments for class can be used only with public and default

      • Public classes can be accessed anywhere
      • The default class can only be accessed by a class inside the same package
Method overrides
    • Methods that inherit from a base class can be overridden in a subclass as needed

    • The overriding method must have the same method name as the overridden method, the parameter list, and the return type

    • Overriding methods cannot use more restrictive access than overridden methods

Super keyword
  • Use super in a Java class to refer to the composition of the base class, for example:

    Class Fatherclass { Public int value; Public void F() {value= -; System. out. println ("Fatherclass.value ="+value); }}class ChildClass extends Fatherclass { Public int value; Public void F() {super.f ();//super points to the parent object of the current object            value= $; System. out. println ("Childclass.value ="+value); System. out. println (value); System. out. println (Super.value);}}
How to construct in inheritance
    • The construction of the subclass must be called during the construction of its base class.
    • Subclasses can use Super (argument_list) to call the construction method of a base class in their own constructor.
      • Use this (argument_list) to invoke another method of construction of this class
      • If you call super, you must write the first line of the subclass construction method
      • If the base class constructor method is not displayed in the constructor of the subclass, the system defaults to calling the base class parameterless construction method
      • If the subclass constructor method does not show the call to the base class construction method, and the base class does not have a parameterless constructor, the compilation error occurs.

A copy of the parameter is copied to the end, leaving the objects in the heap and the references in the stack, as well as the static variables of the data area.

Object class
    • The Object class is the root class for all Java classes
    • If the base class is not indicated in the declaration of the class with the extends keyword, the default base class is the object class

           public class Person {          ...   ...     }

      Equivalent to:

           public class Person extends Object{          ...   ...     }

ToString method

    • The object class is defined with the public String toString () method whose return value is a String type that describes information about the current object
    • The ToString () method of the object class is automatically called when a string is connected to other types of data, such as SYSTEM.OUT.PRINTLN ("info" +person)
    • You can override the ToString () method in a user-defined type as needed

Hashcode explanation

Each object has a unique hash code that can be used to locate the object in memory and determine the location of the object.

Equals method

  • public boolean equals (Object obj) method
    • Logic that defines whether an object is "equal"
  • The Equals method of object is defined as: X.equals (y) returns True if X and Y are references to the same object otherwise false
  • Some of the classes provided by J2SDK, such as String,date, override the Equals method of object, call the Equals method of these classes, X.equals (y), when X and Y refer to objects that are of the same class, and the property content is equal (not necessarily the same object). Returns true otherwise returns false
  • You can override the Equals method in a user-defined type as needed

     Public classtestequals { Public Static void Main(string[] args) {Cat C1 =NewCat (1,2,3); Cat C2 =NewCat (1,2,3);//class cat Overrides the default integrated method from the object class equals ()System. out. println (C1 = = C2);//falseSystem. out. println (C1.equals (C2));//true            the//string class has overridden the method equals ()String S1 =NewString ("Hello"); String s2 =NewString ("Hello"); System. out. println (S1 = = s2);//falseSystem. out. println (S1.equals (S2));//true}}class Cat {intColorintHeight, weight; Public Cat(intColorintHeightintWeight) { This. color = color; This. height = height; This. Weight = weight; } PublicBooleanequals(Object obj) {if(obj = =NULL)return false;Else{if(obj instanceof Cat) {Cat c = (cat) obj;if( This. color = = C.color && This. Height = = C.height && This. Weight = = c.weight) {return true; }               }        }return false; }   }
Object Transformation (casting)
    • A reference-type variable of a base class can "point to" the object of its child class
    • -

"Java Learning Notes" object-oriented

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.