zoukankan      html  css  js  c++  java
  • 暑假自学(15)

    this指针:
    1.this关键字的使用:
    this可以修饰属性、方法、构造器
    2.this修饰属性和方法:
    this理解为:当前对象
    例:
    public class text1 {
    public static void main(String[] args) {
    Student s1 = new Student();
    s1.setage(1);
    System.out.println(s1.getage());
    }
    }
    class Student{
    private int age;
    public void setage(int age) {
    //age = age //类似就近原则,两个age都是形参age
    this.age = age;//加上this指针,确定是数据成员age
    }
    public int getage() {
    return age;
    }
    }
    this调用构造器:
    public Student() {
    System.out.println("hello");
    }
    public Student(int a) {
    this();//写在前面
    System.out.println(a);
    }//this调用必须写在前面

    package和import
    package:为了更好的管理引入包的概念
    1.写在源文件的首行
    2.每"."一次,代表一层文件目录
    3.同一个包下,不能命名同名的接口或类
    import:导入
    1.在源文件中使用import结构导入指定包下的类、接口
    2.声明在包和类之间,多个并列写出
    3.import util.*; *表示包下所有的结构(不包括其子包)

    this实验代码:

    boy.class:

    public class boy {
    private String name;
    private int age;
    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }
    public int getAge() {
    return age;
    }
    public void setAge(int age) {
    this.age = age;
    }
    public boy() {
    }
    public boy(String name, int age) {
    this.name = name;
    this.age = age;
    }
    public void marry(girl girl) {
    System.out.println("娶"+girl.getName());
    }
    public void shout() {
    if(this.age >= 22) {
    System.out.println("可结婚");
    }
    else {
    System.out.println("不可结婚");
    }
    }

    }

    girl.class

    public class girl {
    private String name;
    private int age;
    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }
    public int getAge() {
    return age;
    }
    public void setAge(int age) {
    this.age = age;
    }

    public girl(String name, int age) {
    super();
    this.name = name;
    this.age = age;
    }
    public void marry(boy boy) {
    System.out.println("嫁"+boy.getName());
    }
    public void shout() {
    if(this.age >=20) {
    System.out.println("可结婚");
    }else {
    System.out.println("不可结婚");
    }
    }
    public int compare(girl girl) {
    return this.age - girl.age;

    }
    }

    BoyandGirl:

    public class BoyandGirl {
    public static void main(String[] args) {
    boy boy = new boy("jojo",21);
    boy.shout();

    girl girl = new girl("dio",20);
    girl.compare(girl);
    }
    }

  • 相关阅读:
    Codeforces Round #375 (Div. 2)
    ACM之路(19)—— 主席树初探
    CodeForces 722D Generating Sets
    CodeForces 721D Maxim and Array
    心情--2014区域赛
    【N-Quens II】cpp
    【N-Queens】cpp
    【Unique Paths II】cpp
    【Unique Paths】cpp
    【Palindrome Partitioning】cpp
  • 原文地址:https://www.cnblogs.com/buxiang-Christina/p/13347198.html
Copyright © 2011-2022 走看看