java学习之面向对象(this,static,pakage,import)

转载别人的,用来学习。

this关键字

this关键字在类的方法声明时使用,通常用来区分成员变量与方法中传进来的参数重名的问题,它其实就相当于当前对象本身。

TestThis.java

 

  

public class TestThis {

         /**

          * @param args

          */

         public static void main(String[] args) {

                   A a = new A();

         }

}

class A {

         public A(){

                   new B(this).print();

         }

        

         public void print(){

                   System.out.println("Hello from A!");

         }

}

class B {

         A a;

        

         public B(A a){

                   this.a = a;

         }

        

         public void print(){

                   a.print();

                   System.out.println("Hello from B!");

         }

}

Set  get属性初始化

public class Test2 {

         public static void main(String[] args) {

                   Dog dog = new Dog();

                   //dog.dogName = "旺财";

                   dog.setDogName("旺财");

                   //System.out.println(dog.dogName);

                   System.out.println(dog.getDogName());

         }

}

class Dog {

         String dogName;

         String color;

         int length;

         int weight;

        

         public void setDogName(String _dogName){

                   dogName = _dogName;

         }

        

         public String getDogName(){

                   return dogName;

         }

        

         public void setLength(int _length){

                   length = _length;

         }

        

         public int getLength(){

                   return length;

         }

         }

}

static关键字

在一个类中,被static关键字修饰过的变量,是静态变量,它在该类中是共用的,一个类new出来的多个对象,共用一个static成员变量。

在一个类中被static关键字修饰过的的成员,可以在不被new出来的情况下直接调用,采用“类名.成员变量/方法名”来调用。

在一个类中,被static关键字修饰过的方法,静态方法,静态成员不能够直接调用非静态成员。

package(包):主要用来帮助我们区分相同名称的 java类,包本质上其实就是文件夹。一般来讲给包命名,公司域名的倒序,后面可项目目名,再加具体的模块名。

例:com.bluedot.studentManagement.serveic

package语句一般出现在类的第一行,开始的位置,用“.”来表示包的层次结构。

Import关键字,用来导入其它包中的类。默认java.lang包下的类不需要import

原文地址:https://www.cnblogs.com/shide/p/2963585.html