Java Objects and classes

Source: Internet
Author: User

A class can contain the following types of variables:

    • Local Variables : variables defined in a method, construction method, or block of statements are called local variables. Both the Declaration and initialization of variables are in the method, and the variables are automatically destroyed when the method ends.
    • member variables: member variables are variables that are defined in the class, outside the method body. This variable is instantiated when the object is created. Member variables can be accessed by methods, construction methods, and statement blocks of specific classes within a class.
    • Class variables : Class variables are also declared in the class, outside the method body, but must be declared as static types.
 Public classpuppy{intPuppyage;  PublicPuppy (String name) {//This constructor has only one parameter: nameSystem.out.println ("Passed Name is:" +name); }    Public voidSetage (intAge ) {Puppyage=Age ; }    Public intGetage () {System.out.println ("Puppy's age is:" +puppyage); returnPuppyage; }    Public Static voidMain (String []args) {/*Creating Objects*/Puppy mypuppy=NewPuppy ("Tommy" ); /*use the method to set age*/Mypuppy.setage (2 ); /*call another method to get the age*/Mypuppy.getage (); /*You can also access member variables as follows*/System.out.println ("Variable Value:" +mypuppy.puppyage); }}

Compile and run the above program to produce the following results:

PassedNameis:TommyPuppy's ageis:2variable value:2     

Java Objects and classes

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.