02java基础

1.类的定义

/*
    定义类:
      使用类的形式,对现实中的事物进行描述
      事物: 属性,方法
        属性: 变量
        方法: 这个事物具备的功能

     格式:
       public class 类名{
            属性定义
              修饰符 数据类型 变量名 = 值
            
            方法定义
              修饰符 返回值类型  方法名(参数列表){
                  
              }
       }
       
*/
#Car.java
package cn.jxufe.java.chapter2;

/*
 *  类的方式,描述现实中的事物 小汽车
 *  
 *    小汽车  属性和功能
 *      属性: 颜色  轮胎个数    变量定义
 *      功能: 跑  方法
 *      
 *    属性和方法,都属于类的成员
 *    
 *    属性, 成员变量
 *    方法, 成员方法
 */
public class Car {
    // 定义Car类的属性

    // 定义颜色属性
    String color;
    // 定义轮胎个数

    int count;

    // 定义跑的功能
    public void run() {
        System.out.println("小汽车在跑 ..." + color + "..." + count);
    }

}
#TestCar.java
package cn.jxufe.java.chapter2;

public class TestCar {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Car c = new Car();
        // 对象.调用类中的属性和方法
        c.color = "无色";
        c.count = 5;
        c.run();
    }

}

2.成员变量和局部变量对比

/*
 *  成员变量和局部变量的区别
 *  
 *  1. 定义位置上的区别
 *    成员变量,定义在类中,方法外
 *    局部变量,方法内,语句内
 *    
 *  2. 作用域不同
 *    成员变量,作用范围是整个类
 *    局部变量,方法内,语句内
 *    
 *  3. 默认值不同
 *     成员变量,有自己的默认值
 *     局部变量,没有默认值,不赋值不能使用
 *     
 *  4. 内存位置不同
 *     成员变量,跟随对象进入堆内存存储
 *     局部变量,跟随自己的方法,进入栈内存
 *     
 *  5. 生命周期不同
 *     成员变量,跟随对象,在堆中存储,内存等待JVM清理 , 生命相对较长
 *     局部变量,跟随方法,方法出栈    生命相对较短
 */

3.方法参数是基本数据类型和引用数据类型的区别

#Person.java
package cn.jxufe.java.chapter2.demo2;

public class Person {
    String name;
}
# TestPerson
package cn.jxufe.java.chapter2.demo2;

/*
 *  方法的参数类型,是基本数据类型,引用数据类型
 */
public class TestPerson {
    public static void main(String[] args) {
        int a = 1;
        function(a);
        System.out.println(a);

        Person p = new Person();
        p.name = "张三";
        System.out.println(p.name);

        function(p);

        System.out.println(p.name);
    }

    /*
     * 定义方法,参数类型是引用数据类型 参数是Person类型 p接受的是一个内存的地址 main 中的
     * 变量p function 中的变量p 保存的地址是一样的
     */
    public static void function(Person p) {
        p.name = "李四";
    }

    /*
     * 定义方法,参数类型是基本数据类型
     */
    public static void function(int a) {
        a += 5;
    }
}

4.实例变量和类变量、常量、方法

package cn.jxufe.java.chapter2.demo8;

public class TestCircleWithStaticMembers {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("before creating objects");
        System.out.println("the number of Circle objects is " + CircleWithStaticMembers.numberOfObjects);

        CircleWithStaticMembers c1 = new CircleWithStaticMembers();

        System.out.println("\nAfter creating c1");
        System.out.println("c1: radius " + c1.radius + " and number of Circle objects " + c1.numberOfObjects);
        
        CircleWithStaticMembers c2 = new CircleWithStaticMembers(5);
        
        System.out.println("\nAfter creating c2");
        System.out.println("c1: radius " + c1.radius + " and number of Circle objects " + c1.numberOfObjects);
        System.out.println("c2: radius " + c2.radius + " and number of Circle objects " + c2.numberOfObjects);
    }

}

使用下面的方法进行改正

package cn.jxufe.java.chapter2.demo9;

public class StaticMethod {
    int i = 5;
    static int k = 2;

    public static void main(String[] args) {
        StaticMethod a = new StaticMethod();
        int j = a.i; 
        a.m1(); 
    }

    public void m1() {
        i = i + k + m2(i, k);
        System.out.println("i = " + i);
    }

    public static int m2(int i, int j) {
        return (int) (Math.pow(i, j));
    }

}

5.构造方法

#SimpleCircle
package cn.jxufe.java.chapter2.demo3;

public class SimpleCircle {
    double radius;

    public SimpleCircle() {
        // TODO Auto-generated constructor stub
        radius = 1;
    }

    public SimpleCircle(double radius) {
        this.radius = radius;
    }

    public void setRadius(double radius) {
        this.radius = radius;
    }

    double getArea() {
        return radius * radius * Math.PI;
    }

    double getPerimeter() {
        return 2 * radius * Math.PI;
    }
}
#TestSimpleCircle
package cn.jxufe.java.chapter2.demo3;

public class TestSimpleCircle {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        SimpleCircle circle1 = new SimpleCircle();
        System.out.println("the area of the circle of radius " + circle1.radius + " is " + circle1.getArea());

        SimpleCircle circle2 = new SimpleCircle(25);
        System.out.println("the area of the circle of radius " + circle2.radius + " is " + circle2.getArea());

        SimpleCircle circle3 = new SimpleCircle(125);
        System.out.println("the area of the circle of radius " + circle3.radius + " is " + circle3.getArea());
    }

}

6.private关键字

描述人。Person

属性:年龄。

行为:说话:说出自己的年龄。

#Person.java
package cn.jxufe.java.chapter2.demo4;

public class Person {
    int age;
    String name;

    public  void show() {
        System.out.println(" age= " + age + " name " + name);
    }
}
#TestPerson.java
package cn.jxufe.java.chapter2.demo4;

public class TestPerson {
    public static void main(String[] args) {
        // 创建Person对象
        Person p = new Person();
        p.age = -20; // 给Person对象赋值
        p.name = "人妖";
        p.show(); // 调用Person的show方法
    }
}

通过上述代码发现,虽然我们用Java代码把Person描述清楚了,但有个严重的问题,就是Person中的属性的行为可以任意访问和使用。这明显不符合实际需求。

可是怎么才能不让访问呢?需要使用一个Java中的关键字也是一个修饰符 private(私有,权限修饰符)。只要将Person的属性和行为私有起来,这样就无法直接访问。

#Person.java
package
cn.jxufe.java.chapter2.demo5; public class Person { private int age; String name; // private是成员修饰符,不能修饰局部变量,被private修饰的成员变量,只能在该类的内容使用,超出该类的范围都不能使用。 public void setAge(int age) { if (age < 0 || age > 130) { System.out.println(age + " 不符合年龄范围"); return; } else { this.age = age; } } public void show() { System.out.println(" age= " + age + " name " + name); } }
#TestPerson.java
package
cn.jxufe.java.chapter2.demo5; import cn.jxufe.java.chapter2.demo5.Person; public class TestPerson { public static void main(String[] args) { // 创建Person对象 Person p = new Person(); p.setAge(-20); // 给Person对象赋值 p.name = "人妖"; p.show(); // 调用Person的show方法 } }

 总结:

  类中不需要对外提供的内容都私有化,包括属性和方法。

  以后再描述事物,属性都私有化,并提供setXxx getXxx方法对其进行访问。

注意:私有仅仅是封装的体现形式而已。

7.this关键字

局部变量和成员变量同名问题

不加this,就近原则调用

package cn.jxufe.java.chapter2.demo6;

public class Person {
    int age;
    public void speak() {
        int age = 18;
        System.out.println("age = " + age);
    }
}
package cn.jxufe.java.chapter2.demo6;

public class TestPerson {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Person person = new Person();
        person.age = 28;
        person.speak();
        System.out.println("person.age= " + person.age);
    }

}

加this,指明了调用的是成员变量

package cn.jxufe.java.chapter2.demo6;

public class Person {
    int age;
    public void speak() {
        int age = 18;
        System.out.println("age = " + this.age);
    }
}
package cn.jxufe.java.chapter2.demo6;

public class TestPerson {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Person person = new Person();
        person.age = 28;
        person.speak();
        System.out.println("person.age= " + person.age);
    }

}

this哪个对象调用了this所在的方法,this就代表哪个对象。

8.访问权限

9.java库中的类

9.1Date类

package cn.jxufe.java.chapter2.demo7;

import java.util.Date;

public class DateTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Date date = new Date();
        System.out.println("the elapsed times since Jan 1,1970 is " + date.getTime() + " milliseconds");
        System.out.println(date.toString());
    }

}

9.2Random类

package cn.jxufe.java.chapter2.demo7;

import java.util.Random;

public class ch02RandomTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Random random1 = new Random(3);
        System.out.println("from random1:");
        for (int i = 0; i < 10; i++) {
            System.out.print(random1.nextInt(10)+ " ");
        }

        Random random2 = new Random(3);
        System.out.println("\nfrom random2:");
        for (int i = 0; i < 10; i++) {
            System.out.print(random2.nextInt(10) + " ");
        }
    }

}

10.面向对象的简单应用

10.1贷款的例子

package cn.jxufe.java.chapter2.demo10;

import java.util.Date;

public class Loan {
    private double annuInterestRate;
    private int numberOfYears;
    private double loanAmount;
    private Date loanDate;

    public Loan() {
        // TODO Auto-generated constructor stub
        this(2.5, 1, 1000); // 相当于直接调用下面的构造方法
    }

    public Loan(double annuInterestRate, int numberOfYears, double loanAmount) {
        this.annuInterestRate = annuInterestRate;
        this.numberOfYears = numberOfYears;
        this.loanAmount = loanAmount;
        loanDate = new Date();
    }

    public double getAnnuInterestRate() {
        return annuInterestRate;
    }

    public void setAnnuInterestRate(double annuInterestRate) {
        this.annuInterestRate = annuInterestRate;
    }

    public int getNumberOfYears() {
        return numberOfYears;
    }

    public void setNumberOfYears(int numberOfYears) {
        this.numberOfYears = numberOfYears;
    }

    public double getLoanAmount() {
        return loanAmount;
    }

    public void setLoanAmount(double loanAmount) {
        this.loanAmount = loanAmount;
    }

    public Date getLoanDate() {
        return loanDate;
    }

    public void setLoanDate(Date loanDate) {
        this.loanDate = loanDate;
    }

    public double getMonthlyPayment() {
        double monthlyInterestRate = annuInterestRate / 1200;
        double monthlyPayment = loanAmount * monthlyInterestRate
                / (1 - (1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12)));
        return monthlyPayment;
    }

    public double getTotalPayment() {
        double totalPayment = getMonthlyPayment() * numberOfYears * 12;
        return totalPayment;
    }

}
package cn.jxufe.java.chapter2.demo10;

import java.util.Scanner;

public class TestLoan {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner input = new Scanner(System.in);
        System.out.println("enter annual interest rate,for example,8.25:");
        double annualInterestRate = input.nextDouble();

        System.out.println("enter number of years as an integer: ");
        int numberOfYears = input.nextInt();

        System.out.println("enter loan amount,for example,12000: ");
        double loanAmount = input.nextDouble();

        Loan loan = new Loan(annualInterestRate, numberOfYears, loanAmount);
        
        //注意此处的 printf
        System.out.printf("the loan was created on %s\n " + "the monthly payment is %.2f\n The total paymen is %.2f\n",
                loan.getLoanDate().toString(), loan.getMonthlyPayment(), loan.getTotalPayment());

    }

}

10.2设计栈类

package cn.jxufe.java.chapter2.demo11;

public class StackOfInteger {
    private int[] elements;
    private int size;
    public static final int DEFAULT_CAPACITY = 16;

    public StackOfInteger(int capacity) {
        // TODO Auto-generated constructor stub
        elements = new int[capacity];
    }

    public StackOfInteger() {
        this(DEFAULT_CAPACITY);
    }

    public void push(int value) {
        if (size >= elements.length) {
            int[] temp = new int[elements.length * 2];
            System.arraycopy(elements, 0, temp, 0, elements.length);
            elements = temp;
        }
        elements[size++] = value;
    }

    public int pop() {
        return elements[--size];
    }

    public int getSize() {
        return size;
    }

    public boolean empty() {
        return size == 0;
    }
}
package cn.jxufe.java.chapter2.demo11;

public class TestStackOfInteger {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        StackOfInteger stack = new StackOfInteger();

        for (int i = 0; i < 10; i++) {
            stack.push(i);
        }
        while (!stack.empty()) {
            System.out.print(stack.pop() + " ");
        }
    }

}

猜你喜欢

转载自www.cnblogs.com/xinmomoyan/p/10901882.html