面向对象的特征有哪些方面?
封装 抽象 继承 多态
Java对象和类
package java学习;
public class Dog {
int dogAge;
public Dog (String name){
//构造器
System.out.println("小狗的名字是 "+name);
}
public void setDogAge(int age ){
//传进来的值是age 然后赋值给dogAge
dogAge = age;
}
public int getDogAge(){
System.out.println("小狗的年龄为 "+ dogAge);
return dogAge;
}
public static void main(String[] args) {
Dog dog = new Dog("tommy");
dog.setDogAge(2);
dog.getDogAge();
System.out.println("变量值:"+dog.dogAge);
}
}
Java封装
封装将抽象型函式接口的实现细节部分包装隐藏起来
优点:
减低耦合性,提高代码独立性
类内部可以自由修改
对成员变量控制更精准
隐藏信息,实现细节
package java学习;
public class Encapsulation {
private String name;
private String idNum;
private int age ;
public int getAge() {
return age;
}
public String getName(){
return name;
}
public String getidNum(){
return idNum;
}
public void setAge(int newAge){
age = newAge;
}
public void setName(String newName){
name = newName;
}
public void setIdNum(String newIdNum){
idNum = newIdNum;
}
}
package java学习;
public class RunEncap{
public static void main(String[] args) {
Encapsulation encap = new Encapsulation();
encap.setName("nama");
encap.setAge(16);
encap.setIdNum("123zyn");
System.out.println("Name: "+encap.getName() + " Age " +encap.getAge() +" id :"+encap.getidNum());
}
}
Java继承
package java学习.继承;
public class Animal {
private String name;
private int id;
public Animal(String myName,int myId){
name = myName;
id = myId;
}
public void eat(){
System.out.println(name +"正在吃");
}
public void sleep(){
System.out.println(name +"正在睡");
}
public void introduction(){
System.out.println("大家好!我是" +id + name);
}
public static void main(String[] args) {
Animal a = new Animal("猪猪",12);
a.eat();
a.sleep();
a.introduction();
Peguin p = new Peguin("企鹅",13);
p.eat();
p.sleep();
p.introduction();
Mouse m = new Mouse("老鼠",14);
m.eat();
m.sleep();
m.introduction();
}
}
package java学习.继承;
public class Mouse extends Animal {
public Mouse(String myName, int myId) {
super(myName, myId);
}
}
package java学习.继承;
public class Peguin extends Animal {
public Peguin(String myName, int myId) {
super(myName, myId);
}
}
Super:对父类成员进行访问
This:指向自己的引用
构造器:
子类不继承父类的构造器,它只是调用。如果父类的构造器带有参数,则必须在子类的构造器中显示的通过super调用父类的构造器,并配以适当的参数列表。
package java学习.继承.构造器;
class SuperClass{
private int n;
SuperClass(){
System.out.println("SuperClass()");
}
SuperClass(int n){
System.out.println("SuperClass(int n)");
this.n = n;
}
}
//SubClass类继承
class SubClass extends SuperClass{
private int n;
SubClass(){//自动调用父类的无参构造器
System.out.println("SubClass()");
}
public SubClass(int n){
super(300);//调用父类的有参数构造器
System.out.println("SubClass(int n)" +n);
this.n = n;
}
}
public class TestSuperSub {
public static void main(String[] args) {
System.out.println("--------类继承--------");
SubClass sc1 = new SubClass();
SubClass sc2 = new SubClass(100);
}
}