Java object and class learning, java object Learning

Source: Internet
Author: User

Java object and class learning, java object Learning

Class of the defined object:

  • The State (attribute or feature) of an object refers to the data domains with their current values.
  • The behavior of an object is defined by a method. The method of calling an object is to complete an action of the object.

Use a common class to define objects of the same type. A class is a template, and an object is an instance of a class. You can create multiple instances from one class.

Example:

public class Main{    public static void main(String args[])    {    Circle c1 = new Circle();    System.out.println("The area of the circle of radius " + c1.radius + " is " + c1.getArea());        Circle c2 = new Circle(25);    System.out.println("The area of the circle of radius " + c2.radius + " is " + c2.getArea());    c2.radius = 100;    System.out.println("The area of the circle of radius " + c2.radius + " is " + c2.getArea());        }}class Circle{double radius;Circle() {radius = 1.0;}Circle(double newRadius) {radius = newRadius;}double getArea() {return radius * radius * Math.PI;}}

You can put two classes in the same file, but only one class in the file is public. In addition, the public class must have the same name as the file, as shown above.

Three features of constructor:

1. Must have the same name as the class

2. No return value, even void

3. the constructor is called when an object is created using the new operator. The constructor is used to initialize the object.

After an object is created, its data and methods can be accessed and called using the dot operator (.), that is, the object member access operator.

The data field is called an instance variable and the method is called an instance method.

The data field may also be referenced. The following Student class contains a name data field of the String type:

class Student{String name;int age;boolean isScienceMajor;char gender;}

The default value of the reference data field is null, the default value of the numeric data field is 0, the default value of the boolean data field is false, and the default value of the char data field is '\ u0000'

Test the default value of the data field in the above Student object:

public class Main{    public static void main(String args[])    {     Student student = new Student();     System.out.println("name? " + student.name);  //name? null     System.out.println("age? " + student.age);  //age? 0     System.out.println("isScienceMajor? " + student.isScienceMajor); //isScienceMajor? false     System.out.println("gender? " + student.gender); //gender?         }}

Use classes in the java Library

Date class:

public class Main{    public static void main(String args[])    {    java.util.Date date = new java.util.Date();    System.out.println("The elapsed time since Jan 1, 1970 is " + date.getTime() + " milliseconds");    //The elapsed time since Jan 1, 1970 is 1404740843243 milliseconds    System.out.println(date.toString());    //Mon Jul 07 21:47:23 GMT+08:00 2014    }}

Random class

You can use Math. random () gets a random double value (0.0, 1.0). Another way to generate a random number is to use java. util. the Random class that generates int, long, double, float, and boolean values.

When creating a Random object, you must specify a seed or use the default seed. The no-argument constructor uses the time that has elapsed as the seed.

public class Main{    public static void main(String args[])    {    Random random = new Random();    int Irand = random.nextInt();    int Isrand = random.nextInt(100);    long lrand = random.nextLong();    double drand = random.nextDouble();    float frand = random.nextFloat();    boolean brand = random.nextBoolean();    System.out.println("random.nextint(): " + Irand);    System.out.println("random.nextInt(100) " + Isrand);    System.out.println("random.nextLong() " + lrand);    System.out.println("random.nextDouble() " + drand );    System.out.println("random.nextFloat() " + frand);    System.out.println("random.nextBoolean() " + brand);    }}/*random.nextint(): -678227104random.nextInt(100) 9random.nextLong() 2478178459367264996random.nextDouble() 0.5726788505253162random.nextFloat() 0.5969435random.nextBoolean() false*/

Static variables, constants, and methods

If you want all instances of a class to share data, use static variables (or class variables ). Static variables store variable values in a public memory address, so all objects can modify this variable.

You can call static methods without creating a class instance.

public class Main{    public static void main(String args[])    {    System.out.println("Before creating objects");    System.out.println("The number of Circle objects is " + Circle2.numberOfObjects);  //The number of Circle objects is 0    Circle2 c1 = new Circle2();        System.out.println("\nAfter creating c1");    System.out.println("c1: radius (" + c1.radius +   //c1: radius (1.0) and number of Circle objects (1)    ") and number of Circle objects (" +    c1.numberOfObjects + ")");    Circle2 c2 = new Circle2(5);        c1.radius = 9;    System.out.println("\nAfter creating c2 and modifying c1");    System.out.println("c1: radius (" + c1.radius +  //c1: radius (9.0) and number of Circle objects (2)    ") and number of Circle objects (" +    c1.numberOfObjects + ")");    System.out.println("c2: radius (" + c2.radius +  //c2: radius (5.0) and number of Circle objects (2)    ") and number of Circle objects (" +    c2.numberOfObjects + ")");    }}class Circle2 {double radius;static int numberOfObjects = 0;public Circle2() {radius = 1.0;numberOfObjects++;}Circle2(double newRadius) {radius = newRadius;numberOfObjects++;}static int getNumberOfObject() {return numberOfObjects;}double getArea() {return radius * radius * Math.PI;}}

Static variables and static methods can be used in both instance methods of the class and static methods of the class. However, instance variables and instance methods can only be used in instance methods, cannot be used in static methods

public class Main{int i = 5;static int k = 2;    public static void main(String args[])    {    Main mm = new Main();    int j = mm.i;    mm.m1();    }    public void m1() {    i = i + k + m2(i, k);}        public static int m2(int i, int j) {return (int)(Math.pow(i, j));}}

The package can be used to organize classes. The statement package packagename should first appear in the program;

If no package is declared during class definition

The private modifier can only be accessed in its own class. The default modifier limits the access permission to the package, while the Public modifier does not.

If a class is not defined as public, it can only be accessed in the same package.

Package p1; public class c1 {public int x; int y; private int z; public void m1 () {} void m2 () {} private void m3 (){}}View Codepackage p1; public class c2 {void aMethod () {c1 o = new c1 (); o. x = 1; o. y = 2; o. z = 2; // error o. m1 (); o. m2 (); o. m3 (); // error }}View Codepackage p2; import com.sun.org. apache. xml. internal. security. c14n. helper. c14nHelper; public class c3 {void aMethod () {C1 o = new c1 (); o. x; o. y; // error o. z; // error o. m1 (); o. m2 (); // error o. m3 (); // error }}View Code

The modifier private can only be applied to class members. objects outside the class defining the private data domain cannot access this data domain. In order to access the private data domain, you can provide a get method to return the value of the data field.

To update a data domain, you can provide a set method to set a new value for the data domain.

Public class Circle {private double radius = 1; private static int numberOfObjects = 0; public Circle () {numberOfObjects ++;} public Circle (double newRadius) {radius = newRadius; numberOfObjects ++;} public double getRadius () {return radius;} public void setRadius (double newRadius) {radius = (newRadius> = 0 )? NewRadius: 0;} public static int getNumberOfObjects () {return numberOfObjects;} public double getArea () {return radius * Math. PI ;}}Circle class
public class Main{    public static void main(String args[])    {    Circle myCircle = new Circle(5.0);  //creat a Circle    System.out.println("The area of the circle  of radius "    + myCircle.getRadius() + " is " + myCircle.getArea());        //Increase myCircle's radius    myCircle.setRadius(myCircle.getRadius() * 1.1);    System.out.println("The area of the circle of radius " + myCircle.getRadius() + " is "    + myCircle.getArea());        System.out.println("The number of objrcts created is " + Circle.getNumberOfObjects());}}

Passing an object to a method is actually passing an object reference.

Java only has one way to pass parameters: value transfer. The passed object is actually the reference value of the passed object.

public class Main{    public static void main(String args[])    {    Circle myCircle = new Circle(1);    int n = 5;    printAreas(myCircle, n);    System.out.println("\n" + "Radius is " + myCircle.getRadius());    System.out.println("n is " + n);}        public static void printAreas(Circle c, int times) {    System.out.println("Radius \t\tArea");    while(times >= 0) {    System.out.println(c.getRadius() + "\t\t" + c.getArea());    c.setRadius(c.getRadius() + 1);    times--;    }    }}

 

Object array: an object array is actually an array that references a variable.

public static void main(String args[]){    Circle[] circleArray = new Circle[10];    for(int i = 0; i < circleArray.length; ++i) {    circleArray[i] = new Circle();    }}

 

 


How to Learn java class and Object Technology
Can anyone tell me what to pay attention to when learning Java classes and objects? Class
Specifically, the data structure (attribute) of the object bean is more powerful than that of the human object.
Class is usually used to execute the business logic
Let's talk about food and walking.
Also, classes contain attributes and method classes.
Example

Public class Human
{
Private String hand;
Private String foot;

Public String getFoot (){
Return foot;
}
Public void setFoot (String foot ){
This. foot = foot;
}
Public String getHand (){
Return hand;
}
Public void setHand (String hand ){
This. hand = hand;
}
// Upper attributes

// Action, or method
Public void eating ()
{
System. out. println ("Use your hands for dinner ");
}
}
Separate Two parts of development
Target Audience

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.