1: Basic concepts of the class
The base unit of a Java program is a class, a class is an instance of an object, or an object is a variable of a data type defined by a class. After you have created the class, you can use it to build many of the objects you need. Java turns each executable component into a class.
The class is defined in the following form:
class classname extends superclassname
{
.....
}
Here, classname and Superclassname are valid identifiers. The keyword extends is used to indicate that the classname is a superclassname-derived subclass. There is a class called object, which is the root of all Java classes. If you want to define a direct subclass of object, you can omit the extends clause and the compiler will automatically include it. The following is a simple definition of a class.
Curly braces must be used at the beginning and end of the class definition. You may want to create a rectangular class, then you can use the following code:
public class Rectangle
{
......
}
2: The basic composition of the class
A class typically contains two types of elements, data and functions, which we generally call attributes and member functions, and in many cases we refer to member functions as methods. By tightly combining data with code through classes, the concept of encapsulation that is now very popular is formed. Naturally, the definition of a class should also include the above two parts.
class <classname>
<member data declarations>
<member function declarations>
3: Instance creation of class
In rectangular class rectangle, you might want to write the information about the rectangle to the class, such as: Width,height, of course you can write other information, but perhaps the long and the wide is enough for a simple rectangle. The definition of a class now looks like this:
public class Retangle
{
int width,height;
}
After you have created your own class, you usually need to use it to do some kind of work. You can implement this requirement by defining an instance of the class-object.
Objects are created by new, implementing member functions as follows: Rectangle myrect=new Rectangle, of course, at this point the object myrect did nothing; it only holds the long and wide information of the rectangle. How do we use the data inside the object after we have the object? Here are a few examples:
myrect.width=10;
myrect.height=20;
The member functions of a class are also "." Operator is referenced by the.