I have been learning java for a long time and have not been clear about the objects in java. Today, the landlord has sorted out the objects in java, hoping to help everyone.
To understand and use objects in java, we first understand the construction method and the creation of objects. Classes are the most important kind of data in object-oriented languages, and you can use classes to declare variables. In object-oriented languages, variables declared with classes are called objects.
Different from basic data types, after declaring an object, you must also create an object, that is, assign the variables it owns to the declared object (determine the attributes the object has). When you use a class to create an object, it is also called given. one of this class
instance. In layman's terms, a class is a template for creating objects.
1. Constructor
class Person { int age; String name; Person(){ } }
Person() is a constructor in the Person class. In fact, this method is hidden by java, that is to say, if there is no constructor written in the class, the system will default that the class has a parameterless structure, and there is no statement in the method body. function. Such as
Person(){ } in the Person class, if one or more constructors are defined in the class, then java does not provide a default constructor. as follows:
class Person { int age; String name; Person(){ age=22; name = "Andy Lau" ; } Person(int age,Stirng name){ System.out.println("the man age is"+age+"name: "+name); } }
2 Create objects
class Person { int age; String name; void speak(String name){ System.out.println(name); } } public class OuXiang { public static void main(String[] args) { Person liudehua; // declare object liudehua= new Person(); // assign variables to variables (using new and default constructor) } }
2. Use the new operator and the constructor of the class to assign variables to the declared object, i.e. create the object.
class Person { int age; String name; Person(int age,Stirng name){ System.out.println("the man age is"+age+"name: "+name); } void speak(String name){ System.out.println(name); } } public class OuXiang { public static void main(String[] args) { Person liudehua; // declare the object liudehua= new Person(53,"Andy Lau"); // Assign variables to variables (using new and the constructor in the class) } }
3 Object memory model
null |
---|