Java entry summary part1

class and object

java class class can be imagined as an object, its naming is generally capitalized in the first letter, in this object you can define its properties and methods (I think the method here Similar to the function of the C language, the method is what the object can do. For example, a person is an object with attributes of name, age, and gender. If you eat, you can write the following code:

package javalearn; class Person{

String name;

int age;

char sex;

public static void power(){

System.out.print("I will eat");

}

} public class Learn {

public Static void main(String[] args) { // TODO Auto-generated method stub Person onepeople = new Person(); Onepeople.name = "onepeople's name is Li Si"; System.out.println(onepeople.name); Onepeople.power(); }

}

This code will output: onepeople's name is Li Si. I will eat the

method. The recursive call is similar to the recursive call of the C language function, not much to say.

Encapsulation: Use private

private int age; not this object will not be able to change the age attribute of this object, you should use the individual get() and set() functions, specific usage:

package javalearn ; Class Person{ Private int age; / / set a private property, other objects can not be modified

public int getAge () { / / through the get method, pay attention to the calling method of the main class Return age; }

public void setAge(int age) {//Set by set method, pay attention to the calling method of the main class This.age = age; } } Public class Learn {

    public static void main(String[] args) {         // TODO Auto-generated method stub         Person onepeople = new Person();         onepeople.setAge(30);         System.out.println(onepeople.getAge());     }

}

Constructor:

Constructor name is the same as the class name, no return value, mainly used for initialization of object properties, can be overloaded (there is a knowledge point that calls the no-argument constructor) ). How to use

package javalearn; class Person{  int age;

public Person(int age) {//Remember the name is the same This.age=age; System.out.print(this.age); }

} public class Learn {

    public static void main(String[] args) {         // TODO Auto-generated method stub         Person onepeople = new Person(30);     }

}

Tomorrow continues to inherit. . .