未封装:
public class Person {int age;//年龄
String name;//姓名
public void print()
{
System.out.println("age:"+this.age+" "+"name:"+this.name);
}
}
class Text{
public static void main(String[] args) {
Person person = new Person();//实例化对象
person.age = -100;//赋值
person.name = "张三";
person.print();//执行类中的方法
}
}
运行结果:<br>age:-100 name:张三
封装:
public class Person {private int age;//年龄
private String name;//姓名
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"age=" + this.age +
", name='" + this.name + '\'' +
'}';
}
}
class Text{
public static void main(String[] args) {
Person person = new Person();
person.setAge(20);
person.setName("张三"); ;
String s = person.toString();
System.out.println(s);
}
}
运行结果:
Person{age=20, name='张三'}
继承
public class Office {public void print(){
System.out.println("打印");
}
}
class Word extends Office {
@Override
public void print() {
System.out.println("Word打印");
}
}
class Test{
public static void main(String[] args) {
Word word = new Word();
word.print();
}
}
运行结果:
Word打印
一个Java源文件中可以声明多个class类,但只能有一个public修饰的类。
多态
public class Office {public void print(){
System.out.println("打印");
}
}
class Word extends Office {
@Override
public void print() {
System.out.println("Word打印");
}
}
class Excle extends Office{
@Override
public void print() {
System.out.println("Excel打印");
}
}
class Ppt extends Office{
public void daYin() {//子类可以重写父类方法,也可以自己定义方法
System.out.println("PPT打印");
}
}
class Test{
public static void main(String[] args) {
Office o = new Word();//多种形态,即多态
o.print();
}
}
运行结果:
Word打印
class Test{
public static void main(String[] args) {
Office o = new Excle();
o.print();
}
}
运行结果:
Excel打印
class Test{
public static void main(String[] args) {
Office o = new Ppt();
o.print();
}
}
运行结果:
打印