Understanding and use of get and set methods in Java

Source: Internet
Author: User

Previously seen in Java often a bunch of corresponding set and get, simply know that the set is the value of a pass-through get.

For example:

Books.java

1  PackageTest.testxml;2 3  Public classBooks {4     Private intID;5     PrivateString name;6     Private DoublePrice ;7     PrivateString author;8     9     Ten      Public intgetId () { One         returnID; A     } -      Public voidSetId (intID) { -          This. ID =ID; the     } -      PublicString GetName () { -         returnname; -     } +      Public voidsetName (String name) { -          This. Name =name; +     } A      Public DoubleGetPrice () { at         returnPrice ; -     } -      Public voidSetprice (DoublePrice ) { -          This. Price =Price ; -     } -      PublicString Getauthor () { in         returnauthor; -     } to      Public voidSetauthor (String author) { +          This. Author =author; -     } the}

A books class has several private member variables (private member variables can only be accessed with their own methods in the same class)

So how do the methods in other classes want to access it? This time is accessed through the set and get methods.

Example:

Test01.java

 Public class test01 {    publicstaticvoid  main (string[] args) {                     books b=  New  Books ();               B.setauthor ("Jiarui");        System.out.println (B.getauthor ());  }              

The content of the output is the content "Jiarui" that is set in.

Understanding and use of get and set methods in Java

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.