码迷,mamicode.com
首页 > 编程语言 > 详细

Java面向对象基本特征

时间:2015-04-28 00:04:02      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:java

1、封装性

    一个对象和外界的联系应当通过一个统一的接口,应当公开的公开,应当隐藏的隐藏。

    属性的封装:Java中类的属性的访问权限的默认值是default,要想隐藏该属性或方法,就可以加private(私有)修饰符,来限制只能够在类的内部进行访问。对于类中的私有属性,要对其给出一对方法(getXxx(),setXxx())访问私有属性,保证对私有属性的操作的安全性。 

    方法的封装:对于方法的封装,该公开的公开,该隐藏的隐藏。方法公开的是方法的声明(定义),即(只须知道参数和返回值就可以调用该方法),隐藏方法的实现会使实现的改变对架构的影响最小化。

public class TestDemo {
public static void main(String[] args) {
Person person=new Person();
person.tell();
person.setAge(-20);
person.setName("张三");
person.tell();
}
}
class Person{
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
if(age>0&&age<150){
this.age = age;
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
void tell(){
System.out.println("姓名:"+name+";年龄:"+age);
}
}

备注:(1)Java匿名对象:只需要使用一次的场所。例如:new Person().tell();

      (2)Java构造方法:构造方法名称必须与类名一致,没有返回指,可以重载,主要为类中的属性初始化。

      (3)值传递的数据类型:八种基本数据类型和String(String也是传递的地址,只是String对象和其他对象是不同的,String是final的,所以String对象值是不能被改变的,值改变就会产生新对象。那么StringBuffer就可以了,但只是改变其内容,不能改变外部变量所指向的内存地址)。

           引用传递的数据类型:除String以外的所有复合数据类型,包括数组、类和接口。

public class TestRef4 {
public static void main(String args[])
  {
    int val=10;;
    StringBuffer str1, str2;    
    str1 = new StringBuffer("apples");
    str2 = new StringBuffer("pears");
    
    System.out.println("val:" + val);
    System.out.println("str1 is " + str1);
    System.out.println("str2 is " + str2); 
    System.out.println("...............................");
    
    modify(val, str1, str2);  
    System.out.println("val is " + val);
    System.out.println("str1 is " + str1);
    System.out.println("str2 is " + str2);
  }
 
  public static void modify(int a, StringBuffer r1,StringBuffer r2)
  {      
      a = 0;
      r1 = null;        
      r2.append(" taste good");
      System.out.println("a is " + a);
      System.out.println("r1 is " + r1);
      System.out.println("r2 is " + r2);
      System.out.println("...............................");
  }
}

输出结果为:

val:10
str1 is apples
str2 is pears
...............................
a is 0
r1 is null
r2 is pears taste good
...............................
val is 10
str1 is apples
str2 is pears taste good


2、继承性










本文出自 “IT技术学习与交流” 博客,谢绝转载!

Java面向对象基本特征

标签:java

原文地址:http://qing0991.blog.51cto.com/1640542/1639375

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!