This article brings you the basics of Java: encapsulation - method overloading - introduction to construction methods (with code), so that you can have a preliminary understanding of them, and I hope it will be useful to you. help.
1. Encapsulation
class Dog{ String name;//成员变量 int age; private char genter;//加private变为私有属性,要提供方法才能在外部进行调用 public void setGenter(char genter){ //加if语句可以防止乱输入 if(genter=='男'||genter=='女'){ this.genter=genter;//this.name,这个name为成员变量 }else{ System.out.println("请输入正确的性别"); } } public char getGenter(){ return this.genter; } } public class Test1{ public static void main(String[] args){ Dog one=new Dog(); one.setGenter('女'); System.out.println(one.getGenter()); } }
2. Overloading of methods
Method overloading means that a class can define multiple methods with the same name but different parameters. When called, the corresponding method will be selected based on different parameter lists.
class Cal{ public void max(int a,int b){ System.out.println(a>b?a:b); } public void max(double a,double b){ System.out.println(a>b?a:b); } public void max(double a,double b,double c){ double max=a>b?a:b; System.out.println(max>c?max:c); } } public class Test1{ public static void main(String[] args){ Cal one=new Cal(); one.max(88.9,99.3,120); } }
3. Constructor (constructor)
class Dog{ private String name; private int age; Dog(String name,int age){//构造方法,public可加可不加 this.name=name; this.age=age; System.out.println("名字:"+this.name+"年龄:"+this.age); } Dog(){ } void get(){//普通方法,public可写可不写 System.out.println("我是一个普通方法"); }14 15 }16 public class Test1{ public static void main(String[] args){ Dog one=new Dog("小明",26); Dog two=new Dog(); one.get(); two.get(); } }
This article has ended here. For more other exciting content, you can pay attention to theJava Video Tutorialcolumn of the PHP Chinese website!
The above is the detailed content of Java basics: introduction to encapsulation, method overloading, and construction methods (constructors). For more information, please follow other related articles on the PHP Chinese website!