Java: Object-Oriented Programming

Source: Internet
Author: User

1. Class

The class consists mainly of 3 parts:

    • Class attribute: A property used to describe the things that the class itself abstracts out
    • Class method: Used to describe what this abstracted thing can do
    • Construction methods: Each class has at least one special method that provides an initialization mechanism for creating class objects

Definition of the class:

Modifier class class name "Extends parent class name" "Implements Interface name"

{

Declaration of a class member variable;

class method declaration;

}

. Java source file structure:

The source file for the Java program is a file that ends with ". Java", and only one of the classes in the file is declared as public, and if there is a class declared public, the name of the class must be the same as the ". Java" source file name.

In a source file, you can include three top-level elements: The package Declaration, the Import (Class library import statement), and the class declaration. If they occur at the same time, they must appear in the order of the package, import, class.

Main () Entry method:

 Public Static void Main (String argv[])    {}

The string array in the main () method arvg[] is used to receive user parameters from the command line.

The statement that executes the Java program using the command line consists of four parts: the command name, the command argument (optional), the name of the application (the main class name in the source file), the user input parameters (separated by a space between the parameters)

Access modifier public, private, protect, default

    • Public: can be accessed across classes, and can be accessed across packages
    • Private: The modifier with the narrowest limit of access permissions. can only be accessed by objects of that class, its subclasses are inaccessible, and cross-package access is not allowed
    • Proctet: Can be accessed by the method and subclass method of the class itself, even if the subclass can be accessed in a different package
    • Default: Allow access only in the same package

Construction Method:

The name of the constructed method is the same as the name of the class, and there is no return value of any type, only access modifiers public,private and protected can be used before the method is constructed.

If a class does not have a constructor defined for the class, the system automatically creates a default constructor for the class that is null for the constructor parameters and methods.

Parameters are passed:

There are two types of parameters passed:

  • Basic type ParametersAll of the basic data types are passed, including numeric, Boolean, and so on. In this case, all parameter passing takes the form of a value pass. That is, when passing a parameter into a method, the method obtains only one copy of the value of the parameter. Therefore, the method does not change the value of the parameter variable, only the value of the variable is used.
    •  Public classExample1 { Public Static voidAddintAintb) {intc=a+b; System.out.println ("C=" +c); A=C; }     Public Static voidMain (string[] args) {inta=10; intB=20;        Add (A, b); System.out.println ("A=" +a); }}

      C=30
      a=10

  • Object-referenced parameter , which gets the memory address of the object, so the method can alter the properties in the object, but it cannot alter the object itself.
  •  Public classExample2 { Public Static voidChange (String str,Charch[]) {STR= "Changed"; ch[0]= ' C '; }     Public Static voidMain (string[] args) {String s=NewString ("World"); Charch[]={' H ', ' e ', ' l ', ' l ', ' O '};        Change (S,CH); System.out.println (S+ "+" +string.valueof (CH)); }}

    World and cello

Member method overloading and overloading:

      • Method overloading: Is an object-oriented language attribute that exists only between the parent class and the child class. When a method in a parent class is re-defined in a subclass inheriting from it, the method of the subclass is overloaded with methods of the parent class if the method's name, arguments, and return value types are unchanged, only if the method body has changed.
      • Method overloading, which is a feature of programming language, is independent of object-oriented and exists in the same class. means that multiple methods have the same name, and each method has a unique list of parameters that differs from other methods of the same name.
      • public class Example {    int a=10;    int b=20;    int c=30;        Public Example ()    {        System.out.println ("a+b=" +Add (b)); System.out.println ("a+b+c=" +Add (a,b,c));} public int Add (int x, int. y) {return x+y;} public int Add (int x, int y, int z) {return x+y+Z;} public static void main (string[] args) {new Example ()}} 

        A+b=30
        A+b+c=60

Static statically members:

The static keyword can be used to decorate member variables, methods, and code modules. Variables and methods that use static modifications are called static members. Static members are attached to the class itself, not to member variables of the class.

It is important to note that non-static member variables cannot be accessed directly in a static method.

 public  class   StaticExample1 { static  int  num=10;  public  static  void   main (string[] args) {System.out.println (staticexample1.num); }}
 Public class StaticExample2 {        publicstaticvoid  showstring ()    {        System.out.println ("This is a static method.") );    }      Public Static void Main (string[] args) {        // without creating a class, call the static method         in the class directly Staticexample2.showstring ();    }}

Final keyword:

The final keyword can be used before a class, method, or variable to indicate that the class, method, and variable with which the keyword is decorated have immutable attributes.

    • The final keyword is used before the base data type variable, when the surface of the keyword-modified variable is a constant, after the definition, the value of the variable can no longer be changed, and at the time of definition must be initialized
    • The final keyword is used before the method declaration, and the final modified method is called the final method, which can only be called, cannot be overloaded, but may be overloaded
    • Final keyword is used before the class name, the final keyword-decorated class is called the final class, and the class cannot be inherited by another class
 Public classFinalexample {Static Final Doublepie=3.14;  Public Static voidCircularityarea (String r) {Doubleradius=double.valueof (R). Doublevalue (); System.out.println ("The circularity's area is:" + pie*radius*radius); }         Public Static voidCircularityperimeter (String r) {Doubleradius=double.valueof (R). Doublevalue (); System.out.println ("The circularity's area is:" + pie*radius*2); }     Public Static voidMain (string[] args) {if(args.length!=1) {System.out.println ("Error!"); System.exit (0); } System.out.println ("The circularity's radius is:" +args[0]); Circularityarea (args[0]); Circularityperimeter (args[0]); }}

Determine the class to which the object belongs:

    • Gets the name of the class to which the object belongs: String name = object name. GetClass (). GetName ();
    • Syntax format using the instanceof operator: boolean bool = object name instanceof class name;

Practical Practice:

Simply simulates the functionality of a store customer discount card, customizing the customer class to hold discount card information for customers in a store. In the main class Customerdemo, create an array object of the customer class that contains 3 customer objects to hold the discount card information held by 3 different consumers. Through these 3 objects, we can change the discount price that the user can enjoy in the store according to the amount that the user consumes.

 Public classCustomerdemo {Customer customer[]=NewCustomer[3];  PublicCustomerdemo () {customer[0]=NewCustomer ("c001", "Wangxyw", "Beijing", "[email protected]"); customer[1]=NewCustomer ("c002", "Xu Quan", "Shanghai", "[Email protected],com")); customer[2]=NewCustomer ("c003", "Xu Guang Yang", "Beijing", "[email protected]"); customer[0].buy (2800.00); customer[0].setdiscount (); customer[1].buy (1688.00); customer[1].setdiscount (); customer[2].buy (980.00); customer[2].setdiscount ();  for(inti=0; i<customer.length;i++) {System.out.println ("customer[" + i + "]"); System.out.println ("CardID:" +Customer[i].getcardid ()); System.out.println ("Name:" +customer[i].getname ()); System.out.println ("Cost:" +customer[i].getcost ()); System.out.println ("Discount:" + customer[i].getdiscount () *10); System.out.println ("Address:" +customer[i].getaddress ()); System.out.println ("Email:" + customer[i].getemail () + "\ n"); }                    }     Public Static voidMain (string[] args) {NewCustomerdemo (); }}classcustomer{PrivateString CardID; PrivateString name; Private DoubleCost=0; PrivateString address; PrivateString Email; Private DoubleDiscount = 1;  PublicCustomer (string ID, string name, string add, String email) {CardID=ID;  This. name=name; Address=add;  This. email=email; }        //increase user consumption value after purchasing a product     Public voidBuyDoubleCost ) {         This. cost+=Cost ; }        //change the discount that users can enjoy based on their consumption limit     Public voidSetDiscount () {if(cost>2000.00) Discount-=0.1; Else if(cost>1000.00) Discount-=0.05; }        //methods for getting and setting user addresses     PublicString getaddress () {returnaddress; }     Public voidsetaddress (String address) { This. address=address; }        //methods for getting and setting the user card number     PublicString Getcardid () {returnCardID; }     Public voidSetcardid (String cardID) { This. cardid=CardID; }        //method to get the amount of user consumption     Public DoubleGetcost () {returnCost ; }        //a way to get discounts for users     Public DoubleGetdiscount () {returndiscount; }        //method for obtaining and setting the user's mailbox address     PublicString Getemail () {returnemail; }     Public voidsetemail (String email) { This. email=email; }        //methods for getting and setting the user name     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. name=name; }}

CUSTOMER[0]
cardid:c001
Name:wangxyw
cost:2800.0
discount:9.0
Address:beijing
Email:[email protected]

CUSTOMER[1]
cardid:c002
Name:xu Quan
cost:1688.0
discount:9.5
Address:shanghai
Email:[email protected],com

CUSTOMER[2]
cardid:c003
Name:xu Guang Yang
cost:980.0
discount:10.0
Address:beijing
Email:[email protected]

Java: Object-Oriented Programming

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.