封装
- 封装概念: 在定义一个类时,将类中的属性私有化,需要使用private关键字来修饰,私有属性只能在它所在的类中被访问。为了能让外界访问私有属性,需要提供一些使用public修饰的公有方法,其中包括用于获取属性值getXxx()方法和设置属性值的setXxx()方法。
我自己的理解:将类中属性私有化,不让其他类随意访问,需要调用get/set方法进行访问。
public class Person { private int age; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public void year() { System.out.println("我今年"+age+"岁"); } }
对上面的封装进行修改
public class Student { public static void main(String[] args) { Person p=new Person(); p.setAge(18); p.year(); } }
继承
Java支持单继承,一个子类只有一个直接父类。继承后会获得父类的属性和方法,子类可以有自己的方法。
//父类 public class Person { int age; public void year() { System.out.println("我成年了"); } }
//子类方法 public class Student extends Person{ public void printAge(){ System.out.println("我的年龄是"+age); } }
//测试类 public class TestPerson { public static void main(String[] args) { Student student = new Student(); student.age = 18;// 子类调用父类属性进行赋值 student.printAge();// 子类有自己特殊的方法 student.year();// 子类调用父类的方法 } }
重写
在子类中重写父类的方法,父类的功能不满足需要子类重写。子类修饰方法一定要大于等于父类的方法,覆盖。
public class Person { public void year() { System.out.println("我18岁了"); } }
public class Student extends Person{ @Override public void year() { // TODO Auto-generated method stub super.year(); System.out.println("我成年了"); } }
-
//测试类
public class TestPerson {
public static void main(String[] args) {
Student student = new Student();
student.year();
}
}
重载
在同一个类中,方法名+参数列表不同。
public class Person { public static void main(String[] args) { String name="张三"; year(name); } public static void year() { System.out.println("我18岁了"); } public static void year(String name){ System.out.println("我的名字叫"+name); } }
多态
一种事物有多种形态,格式为父类的引用指向子类的对象,运行时是变成了子类的对象,编译时是父类的对象。
//定义Animal接口 public interface Animal { void shout(); }
//定义Cat类实现Animal接口 public class Cat implements Animal{ @Override public void shout() { System.out.println("喵喵喵..."); } }
//定义Dog类实现Animal接口 public class Dog implements Animal{ @Override public void shout() { System.out.println("旺旺旺..."); } } //测试类 public class TestAnimal { public static void main(String[] args) { //创建Cat对象,使用Animal类型的变量animal引用 Animal animal1 = new Cat() ; //父类的引用指向子类的对象 Animal animal2 = new Dog() ; animal1Shout(animal1); animal1Shout(animal2); } private static void animal1Shout(Animal animal) { // TODO Auto-generated method stub animal.shout(); } }