封装性:不使用属性直接赋值,通过方法进行封装。
优点:提高安全性及复用性。
package fz
class Person{
private String name;
private int age;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
}
public class Test {
public static void main(String[] args) {
Person p1 = new Person();
p1.setName("小明");
p1.setAge(18);
System.out.println(p1.getName()+"的年龄是"+p1.getAge());
}
}
小明的年龄是18
继承:子类拥有父类的属性和方法,将子类共有的特征和行为放入父类
优点:简化代码,提高复用性
package jc;
public class Animal {
String name;
int age;
public void eat() {
System.out.println(name+"在吃");
}
public void sleep() {
System.out.println(name+"在睡");
}
}
class Dog extends Animal{
String color;
public void run() {
System.out.println(name+"在跑");
}
}
class Bird extends Animal{
public void fly() {
System.out.println(name+"在飞");
}
}
package jc;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Dog dog = new Dog();
dog.name = "大黄";
dog.color = "yellow";
dog.eat();
dog.run();
Bird bird = new Bird();
bird.name = "鹦鹉";
bird.eat();
bird.fly();
}
}
大黄在吃
大黄在跑
鹦鹉在吃
鹦鹉在飞
特点:
- 不可多继承——多个父类
- 可多级继承——父类,爷爷类…
- 父类私有的特征不可以继承
- 构造方法不可被继承
原创文章,作者:wdmbts,如若转载,请注明出处:https://blog.ytso.com/272495.html