Basics of Java Classes and Objects

Classes and Objects

Classes, relationships and objects referenced

The relationship between classes and objects

  • Class is a template object is an instance of an object class, a class can have many objects
  • A Java program in the same class can have only one class name, which is not the type of the same name
  • An object can only be created from a class

References and object classes and relationships

  • Reference can only point to the object to which it belongs types of class
  • You can refer to the same type of assignment between
  • Only by pointing to an object reference to the operation of an object, such as a member variable access

method

Parameter passing

Java always uses call by value .

Basic types of value transfer
public class PrimitiveTransferTest {
    public static void swap(int a, int b) {
        int tmp = a;
        a = b;
        b = tmp;
        System.out.println("swap 方法里 a 的值为: " + a + " b的值为: " + b);
    }

    public static void main(String[] args) {
        int a = 6;
        int b = 9;
        swap(a, b);
        System.out.println("交换结束后 a 的值为 " + a + " b的值为 " + b);
    }
}

/**
运行结果:
swap 方法里 a 的值为: 9 b的值为: 6
交换结束后 a 的值为 6 b的值为 9
*/

Analysis chart:

Always java program () method is executed from main, main () method defines a, b two local variables, two main variables in the stack area. When calling swap () method of the main () method, main () method at this time has not ended, the system is a main method and a method of dispensing a two swap stack area, and the main method for storing local variables swap process. the main method a, b method swap variable passed as a parameter, is actually regenerated two variables a, b method stacks in the swap area, and the main method stack area, the value of the variable are assigned a b method swap the stack area a, b parameter (which is initialized). In this case a system memory, there are two variables, two variables b, but different methods exist in the stack area only.

Reference type of transmission parameters
public class ReferenceTransferTest {
    public static void swap(DataWrap dw) {
        int tmp = dw.a;
        dw.a = dw.b;
        dw.b = tmp;
        System.out.println("swap 方法里, a 成员变量的的值为: " + dw.a + " b 成员变量的值为: " + dw.b);
    }

    public static void main(String[] args) {
        DataWrap dw = new DataWrap();
        dw.a = 6;
        dw.b = 9;
        swap(dw);
        System.out.println("交换结束后, a 成员变量的的值为: " + dw.a + " b 成员变量的值为: " + dw.b);
    }
}

/**
swap 方法里, a 成员变量的的值为: 9 b 成员变量的值为: 6
交换结束后, a 成员变量的的值为: 9 b 成员变量的值为: 6
*/

You may doubt that the member variable object dw values ​​of a, b has been replaced, with the front of this basic type of transfer is completely different. This is very easy to feel, incoming call swap method is dw object itself, not its replica. In fact, the transfer is still dw value.

Analysis chart:

Dw assignment as a copy of the system, but the key is just a reference variable dw, it stores the value was just a memory address, the memory address is transmitted to swap the stack area, dw and dw at this time the main stack area of ​​the stack area swap value is the same memory address, the memory address points to the segment DataWrap object heap memory. dw operations on swap stack area, which is the object of DataWrap operation.

Overload

Overload: the same class, the same method name, a different parameter list.

When the calling method is overloaded, the overload which method determines the number and type of parameters to be called exactly matches the method will be executed.

Constructor

The default no-argument constructor

Only if the class does not define any constructor, the system will provide a default constructor. This configuration will all instance fields set to default values.

Custom Builder

When there is a custom class constructor, the system will not provide a default constructor

Static const

public static final double PI = 3.1415926

Static method

When the class is loaded there, and does not depend on any instance of any class.

Recommended by the class name calling, instead of calling the object by way of example, it will be very easy to confuse the concept.

inherit

java use extends inheritance as a keyword, it is interesting extends is an extension of meaning, not inherited. But extends well reflects the relationship of parent and child class, sub-class is an extension of the parent class, sub-class is a special kind of parent. Extend more accurate. ps: this understanding is really abuse ah.

Subclasses override inherited methods (covered)

The method of rewriting follow the "two with a big two small" rule:

  • The name of the same method, the same parameter list

  • Value type subclass method returns the type of the return value should be less than or equal to the parent class method, the method subclass declared class exceptions thrown exception should be smaller than the parent class class method that throw or equivalent

  • Subclass methods access should be greater than or equal access to the parent class method

The method is called the parent class is covered subclass

  • If the method is covered by the example method, the use of super keyword
  • If the method is covered by the class method, the parent class using the class name
  • Subclass can not call the private methods and properties of modified parent class

Subclass call the parent class constructor

  • Subclass can not inherit the parent class constructor. In the constructor for the subclass, if no explicit call using the super parent class constructor, before the system will execute the sub-class constructor, an implicit call parent class constructor with no arguments

  • In a subclass constructor may be used super explicitly call parent class constructor, but super statement must be the first line

Polymorphism

Up type conversion

There are two types of Java reference variable. If compile-time and run-time type types of inconsistencies can occur polymorphism.

  • Compile-time type: determined by the type used when the variable is declared

  • Runtime Type: determined by the object actually assigned to the variable

Sample code:

public class BaseClass {
    public int book = 6;

    public void base() {
        System.out.println("父类的普通方法");
    }

    public void test() {
        System.out.println("父类的test方法");
    }
}

public class SubClass extends BaseClass {
    public String book = "轻量级 Java EE";

    public void test() {
        System.out.println("子类的test方法");
    }

    public void sub() {
        System.out.println("子类的sub方法");
    }

    public static void main(String[] args) {
        BaseClass ploymophicBc = new SubClass();
        System.out.println(ploymophicBc.book);
        ploymophicBc.base();
        ploymophicBc.test();
        // 因为 ploymophicBc 的编译时类型是 BaseClass
        // BaseClass 类没有提供 sub 方法,所以下面代码编译时会出错
        // ploymophicBc.sub();
    }
}

In the above example, ploymophicBc special reference variable, it is BaseClass compile-time type, and the run-time type is SubClass.

ploymophicBc.sub () This line of code at compile-time error, because ploymophicBc BaseClass compile time type, and the sub BaseClass method is not defined, and therefore can not compile time.

Note, however, ploymophicBc.book is 6 rather than "lightweight Java EE". Because the object's instance variables do not have the polymorphism , the system always tries to access the member variables when it compiles the type definitions, rather than running.

Subclasses actually a special parent class, thus allowing the reference to the parent java class objects to sub-class, which is referred to upcast (upcasting), upcast done automatically by the system.

What method can be called, (compile) it depends on the reference type.
Which specific method calls, depending on the reference point of the object instance (runtime).

Downcast

Question: reference variables in your code during compilation, it can only be called with compile-time type of method, but it can not call the method with the runtime type

Solution: cast into a run-time type

Methods: The reference conversion between types can only be between two types of inheritance are, or compiler errors. If you want to convert into a sub-type of class type when compiling a parent class reference variable, then this reference run-time type of the variable must be a subclass type, otherwise a ClassCastException

Sample code:

//创建子类对象  
Dog dog = new Dog();  
  
// 向上类型转换(类型自动提升),不存在风险  
Animal animal = dog;  
  
// 风险演示 animal 指向 Dog 类型对象,没有办法转化成 Cat 对象,编译阶段不会报错,但是运行会报错
Cat cat = (Cat)animal; // 1.编译时按 Cat 类型  2. 运行时 Dog 类型,类型不匹配,直接报错  

instanceof

In order to solve cast, it may lead to abnormal ClassCastException introduced instanceof operator.

Meaning instanceof operator: means for determining the left of the object (called the actual run-time type or genre) is a class or a subclass of the right, the instance of a class. If it returns true, otherwise false.

Before code, casts prior to use instanceof determines:

if (anmial instanceof Cat) {
    Cat cat = (Cat)animal;
}

The final modifier

final modification of class

It can not be inherited

final modification methods

Not covered by subclasses

final modification of variables

Features: Once a variable is initialized, it can not be changed

Initialization: the definition of direct assignment, with the constructor

For basic type field, whose value is immutable.

For reference type variable is concerned, it saved just one reference. final only to ensure that the address referenced by this variable does not change, that has been a reference to the same object. But the contents of the object itself can be changed.

Object class

toString self-describing information for outputting the object.

toString Object class provides the return of the object implementation class "class name + @ + hashCode". Usually you need to override this method.

==

The basic type of variable values, as long as the two variables are equal (no data type is identical), it returns true.

For two reference type variable, only when they point to the same object, judge == will return true.

equals

equals method is an instance method Object class. For reference variable, it returns true if and only point to the same object. General need to override the equals method.

Example override equals method:

    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj !=null && obj.getClass() == Person.class) {
            Person personObj = (Person)obj;
            if (this.getIdStr().equals(personObj.getIdStr())) {
                return true;
            }
        }
        return false;
    }

equals is true, hashCode should be equal, which is a commonly known specifications agreed upon. That equals to true is fully non-necessary condition for equal hashCode.

interface

Design ideas

  • Interface specification embodies the design philosophy and separation, an interface for coupling between components allows the software system is a loosely coupled design

  • A plurality of interface definition is a specification of a common class common behaviors that are communicating with the outer channel, usually it means that the interface defines a set of public methods

definition

  • Modifiers interface, only public or default

  • Because the interface is defined by a specification, the interface where it can not contain constructors and initialization block definitions, contain only static constant, method (only abstract methods, class method and the default), and an internal class, the internal interfaces, the internal pieces move

  • Interface is the only constant in the static constants, default public static final modification

  • Interface in the internal class, the internal interface, internal enumeration, using the modified default public static

  • Interface in the abstract methods can not have a method body, but the class and the default method must have a method body.

Method Description

Abstract methods defined in an interface abstract keyword may be omitted and modifiers, the default modifier is public.

Java 8 new interface allows you to define the default method, using a default modification. By default, the system uses a modified public default method.

Java 8 new private method allows to define the interface.

Java 8 new allows you to define a static method in the interface. Static class interface methods can be implemented inheritance.

use

A class can implement one or more interfaces.

A class implements one or more interfaces, all abstract class interface methods implemented must be rewritten. Otherwise, the class must be defined as abstract classes, interfaces inherit from the parent to the abstract methods reservations.

Interface can not be used to create an instance, but can be used to declare a reference type variable, the variable must point to achieve the object instance of the class interface.

Abstract class

The difference between abstract classes and ordinary classes, can be summarized as "trade-offs."

Too, refers to the ability of a more abstract class, an abstract method of the abstract class can contain

Loss refers to the loss of an ability to abstract class, abstract class can not be used to create instances

Abstract class and normal class differences:

  • Abstract class uses the abstract modification

  • An abstract class can and may comprise a general category, as a member variable, method, constructor, initialization block, inner classes. But it can not be instantiated abstract class, an abstract class constructor call mainly used subclassed

  • An abstract class may not contain abstract methods, but the abstract class contains a method must be defined as an abstract class

Abstract design idea: abstract class is a template pattern design pattern reflected. Abstract class is abstracted from the parent class in the plurality of particular classes, having a higher level of abstraction. Having the same class from the plurality of abstract features an abstract class, a template for the abstract class subclass, the subclass designed to avoid randomness

Inner classes

Members of the inner class

Non-static inner classes
public class Cow {
    private double weight;

    public Cow() {
    }

    public Cow(double weight) {
        this.weight = weight;
    }
    // 定义一个非静态内部类
    private class CowLeg {
        private double length;
        private String color;

        public CowLeg() {}
        public CowLeg(double length, String color) {
            this.length = length;
            this.color = color;
        }
        public double getLength() {
            return this.length;
        }
        public void setLength(double length) {
            this.length = length;
        }
        public String getColor() {
            return this.color;
        }
        public void setColor(String color) {
            this.color = color;
        }
        public void info() {
            System.out.println("当前牛腿的颜色是 " + this.color + ", 长 " + this.length);
            // 直接访问外部类的 private 修饰的成员变量
            System.out.println("该牛腿所属的奶牛重: " + weight);
        }
    }

    public void test() {
        CowLeg cl = new CowLeg(1.12, "黑白相间");
        cl.info();
    }
    public static void main(String[] args) {
        Cow cow = new Cow(378.9);
        cow.test();
    }
}

In the non-static inner class can directly access the private members of the outer class, because it is in a non-static inner class object inside, save an external parasitic class of objects it references. As shown below:

If a local variable outside the class member variables, member variables inside the class with the internal class method of the same name

  • Direct access to local variables

  • this, access to the internal class instance variables

  • External class class name .this.varName access external class instance variables

External members of the class can not directly access non-static inner classes, members of non-static inner classes regardless of what modifiers modified. Only show non-static inner class object is created to access its instance members.

Static inner classes (class inner class)

If using a modified static inner class, then this internal class belongs outside the class itself, not part of an object outside the class. Therefore also called class inner class. That static inner class is a static member outside the class.

Static inner class can contain static members, may also contain non-static member.

Static inner classes can not access instance members of the outer class, class members can only be accessed outside the class.

External class still can not directly access member static inner classes, but you can use the class name static inner classes as the caller to access class members static inner classes, you can also use static inner class object as the caller to access the instance of the static inner classes member.

Addition to the external access to internal class class

Local access to the internal classes outside of the outer class (including static and non-static, two), the internal class can not use private modification, the modified private inner class can only be used inside the outer class. For other classes internal access modifiers, modifier access the fields range.

  • Access specifier omitted internal class can only be accessed by other classes in the same package with the external class

  • Use the protected modified inner classes, subclasses may be in the same package to access other classes and classes outside the external class

  • Use the public modifier inner classes can be accessed from anywhere

A non-static inner classes outside the outer class

Because the object must be non-static inner class of parasites in the object outside the class where, before creating a non-static inner class object, you must first create its external object.

Sample code, as follows:

public class Out {
    // 使用默认访问控制符,同一个包中的其他类可以访问该内部类
    class In {
        public In(String msg) {
            System.out.println(msg);
        }
    }
}
public class CreateInnerInstance {
    public static void main(String[] args) {
        Out.In in = new Out().new In("Test Msg");
        /*
        上面代码可以改为如下三行代码
        使用 OutterClass.InnerClass 的形式定义内部类变量
        Out.In in;
        创建外部类实例,非静态内部类实例将寄生在该实例中
        Out out = new Out();
        通过外部类实例和new来调用内部类构造器创建非静态内部类实例
        in = out.new In("Test Msg");
        */
    }
}

The following defines a subclass inherits In non-static inner class class class Out

public class SubClass extends Out.In{
    // 显示定义 SubClass 的构造器
    public SubClass(Out out){
        out.super("hello");
    }
}

The above may seem strange code is, in fact, quite normal: In non-static inner class class constructor must use external object to call, on behalf of the code that calls the constructor In super class, and out represents the external object.

If you need to create SubClass object, you must create an Out object. Because SubClass non-static inner classes In a subclass of non-static inner classes In the object there must be a reference to the object Out, subclass SubClass should hold objects in a reference to the object Out. Passed to the constructor when creating objects SubClass Out objects, where the object is SubClass Out the corresponding reference object points.

Combine the above two pieces of code, non-static inner classes In SubClass objects and objects must have a reference point to Outer objects, distinguish different objects incoming Out When you create two kinds of objects: When a non-static inner class object is created In class when, must be called by the new keyword Outer objects; SubClass when creating an object class, the object must be used as Outer caller to call the constructor in class

Internal class used in addition to the external static class

No need to create an external class object because static inner classes are related classes outside of class, so creating a static inner class object.

public class CreateStaticInnerInstance {
    public static void main(String[] args) {
        StaticOut.StaticIn in = new StaticOut.StaticIn();
        /* 上面的代码可改为如下两行代码
        使用 OuterClass.InnerClass 的形式定义内部类变量
        StaticOut.StaticIn in;
        通过 new 调用内部类构造器创建静态内部类实例
        in = new StaticOut.StaticIn();
        */
    }
}

There is no need to use an external class object constructor when called static inner classes, so create a subclass static inner classes are also relatively simple. The following code defines the subclass of an empty class is a static static inner StaticIn

public class StaticSubClass extends StaticOut.StaticIn {}

Partial inner class

Anonymous inner classes

Creates anonymous inner class for creating class used only once, immediately create an anonymous inner class instance of the class, the class definition immediately disappear, anonymous classes can not be reused.

Anonymous class is used to create an instance of an interface or abstract class.

Not anonymous inner classes defined constructor. Because anonymous inner class is not a class name, all can not be defined constructor. However, anonymous inner classes can be defined initialization block, the constructor things may be done by way of example need to complete initialization block.

Anonymous inner classes defined in the following format:

new 实现接口 | 抽象父类构造器(实参列表)
{
    匿名内部类的类体部分
}

Create anonymous inner classes are the most common way is to create an interface type of the object, as follows

public interface ProductA {
    public double getPrice();
    public String getName();
}
public class AnonymousTest {
    public void test(ProductA p) {
        System.out.println("Buy a" + p.getName() + "Cost " + p.getPrice());
    }
    public static void main(String[] args) {
        AnonymousTest ta = new AnonymousTest();
        // 调用 test() 方法时,需要传入一个 Product 参数
        // 此处传入其匿名实现类的实例
        ta.test(new ProductA() {
            @Override
            public double getPrice() {
                return 567.8;
            }

            @Override
            public String getName() {
                return "APG Card";
            }
        });
    }
}

When to create an anonymous inner class by inheriting the abstract parent class, anonymous inner classes and will have the same parent class constructor parameter list. Look at the following piece of code

public abstract class Device {
    private String name;
    public abstract double getPrice();
    public Device() {};
    public Device(String name) {
        this.name = name;
    }
    public String getName() {
        return this.name;
    }
    public void setName(String name) {
        this.name = name;
    }
}
public class AnonymousInner {
    public void test(Device d) {
        System.out.println("Buy a" + d.getName()+ "Cost" + d.getPrice());
    }
    public static void main(String[] args) {
        AnonymousInner ai = new AnonymousInner();
        // 调用有参数的构造器创建 Device 匿名实现类的对象
        ai.test(new Device("电子显示器") {
            @Override
            public double getPrice() {
                return 67.8;
            }
        });

        // 调用无参数的构造器创建 Device 匿名实现类的对象
        Device d = new Device() {
            // 初始化块
            {
                System.out.println("匿名内部类的初始化块");
            }
            // 实现抽象方法
            @Override
            public double getPrice() {
                return 56.2;
            }
            // 重写父类的实例方法
            public String getName() {
                return "keyboard";
            }
        };
        ai.test(d);
    }
}

I welcome the attention of the public number

Guess you like

Origin www.cnblogs.com/Tianny/p/11609889.html