Java初学者总结(第一次用Markdown)
七月八日
1.使用set() 对私有属性进行更改
代码示例
package richanglianxi;
public class lianxi
{
public static void main(String[] args)
{
Student c=new Student(“张浩宇”,20185774);
System.out.println(c.setNumber(20185774));
System.out.println(c.setName("张浩宇"));
}
}
class Student
{
private String name;
private int number;
Student(String name,int number)
{
this.name=name;
this.number=number;
}
public String setName(String name)
{
this.name = name;
return name;
}
public int setNumber(int number)
{
this.number = number;
return number;
}
}
在类Student中定义私有属性name和number,因此在类外部无法直接对私有属性进行访问。故使用public int setNumber(int number)。
方法的构建(减少在逐个初始化产生麻烦)
代码示例:
可直接一次性输入name和number不用逐个初始化。
3.继承(Inheritance)
clss 父类
{
//定义父类
}
class 子类 extends 父类
{
//用extends关键字实现类的继承
}
示例
package richanglianxi;
public class lianxi
{
public static void main(String[] args)
{
student c=new student(“张浩宇”,20185774,“tjut”);
System.out.print(c.name+" “+c.number+” "+c.schoolName);
}
}
class person
{
public String name;
public int number;
}
class student extends person
{
String schoolName;
student(String name,int number,String schoolName)
{
this.name=name;
this.number=number;
this.schoolName=schoolName;
}
}
解析
class student是person的类,其中student是person的子类。
父类中已出现的属性不需要在子类中进行声明!