What is a class? (Review) Something like a design document ・ What to define -Status (status): Variable (field) -Behavior (behavior): method
--Entity created from design document (class) --Multiple generation is possible
Class name instance variable name(freedom) =new class name(argument)[Constructor specification];
Store the generated instance in a variable Notable here! !! __ Class type (reference type) instance variable __
All Java variables are statically typed to declare class types
--A special method that performs initialization processing when creating an instance --Constructor features --The method name is the same as the class name --No return value --There may be multiple constructors with different arguments --Constructor is optional
//Person class
public class Person {
public Person(){
age = 1;
}
public Person(int a){
age = a;
}
public Person(String a){
age = a;
}
public void printAge(){
System.out.println("I"+age+"I'm old");
}
}
}
//main class
public static void main(String args[]){
Person p1 = new Person();
p1.printAge();
int num1 = 29;
Person p2 = new Person(num1){
p2.printAge();
}
String num2 = "29";
Person p3 = new Person(num2){
p3.printAge();
}
}
Access to static fields and static methods --Can be used without instantiating fields and methods with static keywords
Contents | How to use |
---|---|
Use static method | name of the class.Method name(argument) |
Use static fields | name of the class.Field name |
--static field --Only one variable value can be held → Overwritten each time it is stored --static method --You cannot use methods without static or fields without static in the same class from within static methods. --Accessible by creating an instance in a static method
--When using classes from other packages --Specify directly in the code with "package name.class name" --Used in import declaration --import Other package name. Class name; --import package name. * (All classes);
Recommended Posts