Java: Object-oriented Programming

Source: Internet
Author: User

Java: Object-oriented Programming

1. Class

The class consists of three parts:

  • Class Attribute: used to describe the attributes of the things abstracted by the class itself.
  • Class Method: used to describe what this abstract thing can do
  • Constructor: each class has at least one special method, which provides the initialization mechanism for creating class objects.

 

Class Definition:

[Modifier] class name [extends parent class name] [implements interface name]

{

Declaration of class member variables;

Class method declaration;

}

 

. Java source file structure:

The source file of the Java program is a java ". At the same time, only one class in the file can be declared as public class. If there is a class declared as public, the class name must be the same as". java "source file name is the same.

A source file contains three top-level elements: package (package Declaration), import (class Library import Statement), and class (class Declaration ). If both of them appear, they must appear in the order of package, import, and class.

 

Main () entry method:

public static void main(String argv[])    {}

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

The statements for executing a Java program using command lines are composed of four parts: command name, command parameter (optional), and application name (that is, the main class name in the source file ), user-input parameters (multiple parameters are separated by spaces)

 

Access modifiers public, private, protect, and default

  • Public: Cross-class access and cross-package access
  • Private: modifier with the strictest access permission limit. It can only be accessed by objects of the class, and its subclass cannot be accessed, not cross-package access.
  • Proctet: can be accessed by methods and subclass methods of the class, even if the subclass can be accessed in different packages
  • Default: only allow access in the same package

 

Constructor:

The constructor name is the same as the class name, and there is no return value of any type. Before constructor, you can only use the access modifiers public, private, and protected.

If no constructor is defined in a class, the system automatically creates a default constructor for the class. The constructor parameters and methods are empty.

 

Parameter transfer:

There are two types of parameters passed:

  • Basic type parametersAll data types are passed, including numeric and Boolean. In this case, all parameters are passed by value. That is, when a parameter is passed to the method, the method obtains only a copy of the parameter value. Therefore, the method does not change the value of the parameter variable and only uses the value of the variable.
    • public class Example1 {        public static void add(int a, int b)    {        int c=a+b;        System.out.println("c="+c);        a=c;    }    public static void main(String[] args) {        int a=10;        int b=20;                add(a,b);        System.out.println("a="+a);    }}

      C = 30
      A = 10

  • Object Reference parametersThe method obtains the memory address of the object. Therefore, the method can change the attributes of the object, but cannot change the object itself.
  • public class Example2 {        public static void change(String str, char ch[])    {        str="Changed";        ch[0]='C';    }    public static void main(String[] args) {        String s=new String("World");        char ch[]={'H','e','l','l','o'};                change(s,ch);        System.out.println(s+ " and "+ String.valueOf(ch));    }}

    World and Cello

 

Overload and overload of member methods:

    • Method overload: This is an object-oriented language feature that exists only between the parent class and the Child class. When a method in the parent class is redefined in its subclass, if the method name, parameter, and return value type of the method remain unchanged, only when the method body changes, the subclass method overload the method of the parent class.
    • Method overload is a feature of all programming languages. It is independent of object-oriented and exists in the same class. Multiple methods have the same name. Each method has a unique list of parameters different from other methods with the same name.
    • public class Example {    int a=10;    int b=20;    int c=30;        public Example()    {        System.out.println("a+b="+add(a,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 members:

Static keywords can be used to modify member variables, methods, and code modules. Static modified variables and methods are called static members. Static members are attached to the class, not the member variables of the class.

Note that you cannot directly access non-static member variables in static methods.

public class StaticExample1 {        static int num=10;    public static void main(String[] args) {        System.out.println(StaticExample1.num);    }}
Public class StaticExample2 {public static void showString () {System. out. println ("This is a static method. ");} public static void main (String [] args) {// directly call the static method StaticExample2.showString () in the class without creating a class ();}}

 

Final keywords:

The final keyword can be used before classes, methods, and variables to indicate the classes, methods, and variables modified by the keyword.

  • The final keyword is used before a variable of the basic data type. At this time, the variable modified by this keyword is a constant. After definition, the value of this variable cannot be changed and must be initialized during definition.
  • Before the final keyword is used for method Declaration, the final-modified method is called the final method. This method can only be called but cannot be overloaded.
  • The final keyword is used before the class name. The class modified by the final keyword is called the final class, which cannot be inherited by other classes.
public class FinalExample {    static final double pie=3.14;        public static void circularityArea(String r)    {        double radius=Double.valueOf(r).doubleValue();        System.out.println("The circularity's area is: "+ pie*radius*radius);    }        public static void circularityPerimeter(String r)    {        double radius=Double.valueOf(r).doubleValue();        System.out.println("The circularity's area is: "+ pie*radius*2);    }    public static void main(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]);    }}

 

Class to which the object belongs:

  • Get the name of the class to which the object belongs: String name = Object name. getClass (). getName ();
  • Syntax format for using the instanceof OPERATOR: boolean bool = Object Name instanceof class name;

 

Practical exercises:

A simple simulation of a store Customer discount card function, custom Customer class is used to save the Customer discount card information in a store. In the merdemo of the main class, create an array object of the Customer class. The data object contains three Customer objects, which are used to save the discount card information held by three different consumers. Through these three objects, you can change the discount price you can enjoy in this store based on the amount you consume.

Public class CustomerDemo {Customer customer [] = new Customer [3]; public CustomerDemo () {customer [0] = new Customer ("c001", "wangxyw", "BeiJing ", "wangxyue@cn.ibm.com"); customer [1] = new Customer ("c002", "Xu Quan", "ShangHai", "chunticha @ yahoo, com "); customer [2] = new Customer ("c003", "Xu Guang Yang", "BeiJing", "xugy@hotmail.com"); customer [0]. buy (2800.00); customer [0]. setDiscount (); customer [1]. buckets (1688.00); customer [1]. setDiscount (); customer [2]. buckets (980.00); customer [2]. setDiscount (); for (int I = 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 void main (String [] args) {new CustomerDemo () ;}} class Customer {private String cardID; private String name; private double cost = 0; private String address; private String email; private double discount = 1; public Customer (String id, String name, String add, String email) {cardID = id; this. name = name; address = add; this. email = email;} // Add the public void buy (double cost) {this. cost + = cost;} // you can change the public void setDiscount () {if (cost> 2000.00) discount-= 0.1 based on your consumption quota; else if (cost> 1000.00) discount-= 0.05;} // The method used to obtain and set the user address public String getAddress () {return address;} public void setAddress (String address) {this. address = address;} // public String getCardID () {return cardID;} public void setCardID (String cardID) {this. cardID = cardID;} // method for obtaining the user's consumption amount public double getCost () {return cost;} // method for obtaining the user's discount value public double getDiscount () {return discount;} // public String getEmail () {return email;} public void setEmail (String email) {this. email = email;} // public String getName () {return name;} public void setName (String name) {this. name = name ;}}

Customer [0]
CardID: c001
Name: wangxyw
Cost: 2800.0
Discount: 9.0
Address: BeiJing
Email: wangxyue@cn.ibm.com

Customer [1]
CardID: c002
Name: Xu Quan
Cost: 1688.0
Discount: 9.5
Address: ShangHai
Email: chunticha @ yahoo, com

Customer [2]
CardID: c003
Name: Xu Guang Yang
Cost: 980.0
Discount: 10.0
Address: BeiJing
Email: xugy@hotmail.com

 

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.