Java Object-oriented programming

Source: Internet
Author: User

I. Classes and Object objects

Object-An entity used to describe an objective thing, consisting of a set of attributes and methods;

Attribute--The object has a variety of your characteristics, such as the cashier's age, height, weight;

Method-The operation of the object, such as cashier's receipt of silver, printing bill, swipe card, etc.

Class-A set of objects that have the same properties and methods, a class is an object's abstraction, and the object is the concrete of the class;

Method of the class--used to complete a particular application function and return the result;

 Public classVisitor {//Create a class      PublicString name;  Public intAge ; //Defining Methods     Public voidBookticket () {if(Age >= && Age < 65) {System.out.println (name+ "Age +", "20¥"); }Else if(Age >= && Age < 20) {System.out.println (name+ "Age is" + Ages + ", Priceticket ticket for 10¥"); }Else{System.out.println (name+ "Age +", free to visit "); }    }}
 Public classVistortest { Public Static voidMain (string[] args) {Scanner Scanner=NewScanner (system.in); String Visname= ""; intVisage = 0;  Do{System.out.print ("Please enter your name:"); Visname=Scanner.next (); System.out.print ("Please enter your Age:"); Visage=Scanner.nextint (); Visitor v=NewVisitor (); V.age=visage; V.name=Visname;        V.bookticket (); }  while(!" N. Equals (Visname));    Scanner.close (); }}
Method parameters (memory allocation)

Basic data type: allocation in the stack, the variable name points to a specific value, the variable is immediately assigned to his memory space after the declaration, the assignment between the basic types is to create a new copy; "= =" and "! =" are in comparison values; Basic type variables are created and destroyed quickly; Reference data types: allocation in the heap , the heap read and write speed is far inferior to the stack; the variable name points to the memory address of the stored data object, that is, the variable name points to the hash value, and it points to the object entity (the specific value) in a special way (like the C pointer), which does not allocate memory, only stores a memory address; "and"! = "is the same as comparing two references, you need to implement the Equals () method; The class object needs to be destroyed by the JVM;

Construction method

Each class has a default construction method, such as the above program, this method is fixed cumbersome, with the use of parameter construction method is much easier, after writing the construction method, will replace the class default construction method;

 public  class   voter { static  int   count;  private  static  final  int  total = 100< span> private   String name;  public   voter (String name) { this . Name = name; }    ......          }
 Public class Main {    publicstaticvoid  main (string[] args) {        voter Zhang=  New voter ("Zhang San");         New Voter ("John Doe");         New Voter ("Wang Dance");        ......    }}
Method overloading

 Public classADD { Public intAddsum (intNUM1,intnum2) {        return(NUM1 +num2); }     Public intAddsum (intNUM1,intNUM2,intnum3) {        return(NUM1 + num2 +num3); }     Public DoubleAddsum (DoubleNUM1,Doublenum2) {        return(NUM1 +num2); }     Public DoubleAddsum (DoubleNUM1,DoubleNUM2,Doublenum3) {        return(NUM1 + num2 +num3); }}
 Public classCalc { Public Static voidmain (String [] ages) {int[] A =New int[5]; int[] s =New int[9]; ADD sum=NewAdd (); System.out.println (Sum.addsum (2.2, 3.3)); System.out.println (Sum.addsum (3, 5)); System.out.println (Sum.addsum (3, 5, 3.3));    System.out.println (); }}
this keyword

Call Properties

this. Health =; this. Name = "Zhang San"

Calling methods

this. Print ();

Call construction method

 This ();         // if used, must be the first statement in the constructor method  This
Ii. Encapsulation and Inheritance encapsulation

Encapsulation is to say that some information hidden in the class, do not let external programs directly access, but through the method provided by the class to achieve the operation and access to the internal shadow information;

The advantages of encapsulation: To prevent the property from being modified incorrectly, to improve the loose coupling between systems, to improve the system's independence, to improve the reusability of software, and to reduce the risk of building large-scale system;

Encapsulation principle: ① to hide as many things as possible, to provide interfaces externally; ② hide all the attributes;

Encapsulation Step: ① Modify the visibility of the property (set to private), ② create the public Getter/setter method, ③ Add the attribute control statement in the Getter/setter method;

/*** The creation process of standard JavaBean*/ Public classJavaBean {//First step: Create a private property    PrivateString name; Private intID; Private intAge ; PrivateString address; //Step two: Production getter and Setter methods     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     Public intGetID () {returnID; }     Public voidSetID (intID) {
if (ID < 0)
ID = 0
This. ID =ID; } Public intGetage () {returnAge ; } Public voidSetage (intAge ) {
if (age < 0)
Age = 0
This. Age =Age ; } PublicString getaddress () {returnaddress; } Public voidsetaddress (String address) { This. Address =address; } //Step Three: Create a parameterless constructor and a parametric constructor PublicJavaBean () {} PublicJavaBean (String name,intIdintAge , String address) { This. Name =name; This. ID =ID; This. Age =Age ; This. Address =address; } @Override PublicString toString () {return"javabean{" + "name=" + name + ' \ ' + ", id=" + ID + ", age=" + Age + ", address= ' + address + ' \ ' + '} '; }}
Use of packages

JDK Package provides: ①java.lang: Automatic introduction of Virtual machine; ②java.util: provide some practical classes; ③java.io: input, output;

In order to use other classes that are not in the same package, you need to import the class using the Import keyword in your program;

 PackageCom.ibeifeng.java.oop.javabean;ImportCom.ibeifeng.java.oop.buytickets.Visitor;//Import the Visitor class in the Buyticket package Public classUser { Public Static voidmain (String [] args) {Visitor user=NewVisitor (); User.Name= "John Doe"; User.age= 22;        User.bookticket (); //if the current package and the import package have duplicate names, name will use the full path.//If you do not use the full path, then the default is the imported class;//Visitor user1 = new Visitor ();Com.ibeifeng.java.oop.javabean.Visitor user1 =NewCom.ibeifeng.java.oop.javabean.Visitor (); User1.name= "Zhang San"; User1.age= 55;    User1.bookticket (); }}
Member Variable access rights control

Modify variables by keyword to control access

Iii. inheritance and polymorphic static keywords

Static variables have only one piece of control in memory, and the actual variable, each case will re-open the memory space;

When static variables are not the same, they are executed according to the defined order;

When the static variable and the code fast variables in the same time, the first definition of re-assignment;

An instance method can call a static method directly, but a static method cannot call an instance method directly, and must be instantiated using new after the call. A static variable cannot be defined in an instance method.

Static code blocks: initializing static variables

Constructor method: Initialize instance variables

Inherited

The common or repeated attribute methods are extracted separately, packaged by class, and not extracted for individuality, and retained by each other;

Inheritance is the inheritance of all the attributes and methods of the parent class.

The inherited class is the parent class, the class that is actively inheriting is a subclass, and the subclass (A) inherits the parent class using the keyword extends (B)

Only single inheritance is supported in a single--java, that is, a class intelligence has a direct parent class

 Public class A extends B () {}     A inherits the parent class B

Transitive--a inheritance b,b inherits C, then a inherits C, that is, a class can indirectly have more than one parent class

Subclasses can inherit from the parent class, and can have their own attributes, but the parent class cannot inherit the child class

This: object of this class

Super: Parent Class object

When a subclass is instantiated, the non-parametric construction method of the parent class is executed first

If the parent class has a parameter constructor, it must display an argument-free constructor;

Specifies the parameter constructor that invokes the parent class, using the Super keyword:

Public A (string name) {  Super("Xiao Wang");          System.out.println ("constructor of the subclass:" + name);  }

The Super keyword to access the members of the parent class:

Super can only appear in sub-class methods and construction release;

When super calls the constructor method, it can only be the first sentence;

Super cannot access the private members of the parent class;

Iv. abstract classes and interfaces

V. Anomalies

Java Object-oriented programming

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.