Sunday, February 18, 2018

Java class


https://docs.oracle.com/javase/tutorial/java/javaOO/classdecl.html
https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html
https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html


class MyClass extends MySuperClass implements YourInterface {
    // field, constructor, and
    // method declarations
}

means that MyClass is a subclass of MySuperClass and that it implements the YourInterface interface.
In general, class declarations can include these components, in order:
    1. Modifiers such as publicprivate, and a number of others that you will encounter later.
    2. The class name, with the initial letter capitalized by convention.
    3. The name of the class's parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
    4. A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.
    5. The class body, surrounded by braces, {}.
    There are several kinds of variables:
    • Member variables in a class—these are called fields.
    • Variables in a method or block of code—these are called local variables.
    • Variables in method declarations—these are called parameters.
    All variables must have a type. You can use primitive types such as intfloatboolean, etc. Or you can use reference types, such as strings, arrays, or objects.
    • the first letter of a class name should be capitalized, and
    • the first (or only) word in a method name should be a verb.
    Methods:
    method declarations have six components, in order:
    1. Modifiers—such as publicprivate, and others you will learn about later.
    2. The return type—the data type of the value returned by the method, or void if the method does not return a value.
    3. The method name—the rules for field names apply to method names as well, but the convention is a little different.
    4. The parameter list in parenthesis—a comma-delimited list of input parameters, preceded by their data types, enclosed by parentheses, (). If there are no parameters, you must use empty parentheses.
    5. An exception list—
    6. The method body, enclosed between braces—the method's code, including the declaration of local variables, goes here.
    method names should be a verb in lowercase or a multi-word name that begins with a verb in lowercase, followed by adjectives, nouns, etc. In multi-word names, the first letter of each of the second and following words should be capitalized. Here are some examples:
    run
    runFast
    getBackground
    getFinalData
    compareTo
    setX
    isEmpty

    Overloading Methods

    methods within a class can have the same name if they have different parameter lists 
    public class DataArtist {
        ...
        public void draw(String s) {
            ...
        }
        public void draw(int i) {
            ...
        }
        public void draw(double f) {
            ...
        }
        public void draw(int i, double f) {
            ...
        }
    }

    Constructor

    Default Constructor:
    You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass. In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does. If your class has no explicit superclass, then it has an implicit superclass of Object, which does have a no-argument constructor.

    Arbitrary Number of Arguments

    You can use a construct called varargs to pass an arbitrary number of values to a method. You use varargs when you don't know how many of a particular type of argument will be passed to the method. It's a shortcut to creating an array manually (the previous method could have used varargs rather than an array).
    To use varargs, you follow the type of the last parameter by an ellipsis (three dots, ...), then a space, and the parameter name. The method can then be called with any number of that parameter, including none.
    public Polygon polygonFrom(Point... corners) {
        int numberOfSides = corners.length;
        double squareOfSide1, lengthOfSide1;
        squareOfSide1 = (corners[1].x - corners[0].x)
                         * (corners[1].x - corners[0].x) 
                         + (corners[1].y - corners[0].y)
                         * (corners[1].y - corners[0].y);
        lengthOfSide1 = Math.sqrt(squareOfSide1);
    
        // more method body code follows that creates and returns a 
        // polygon connecting the Points
    }
    printf method:
    public PrintStream printf(String format, Object... args)
    
    allows you to print an arbitrary number of objects. It can be called like this:
    System.out.printf("%s: %d, %s%n", name, idnum, address);
    
    or like this
    System.out.printf("%s: %d, %s, %s, %s%n", name, idnum, address, phone, email);

    Instantiating a Class: new Operator

    The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor.

    Note: The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you are creating an "instance" of a class, therefore "instantiating" a class.
    The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate.
    The new operator returns a reference to the object it created. This reference is usually assigned to a variable of the appropriate type, like:
    Point originOne = new Point(23, 94);
    
    The reference returned by the new operator does not have to be assigned to a variable. It can also be used directly in an expression. For example:
    int height = new Rectangle().height;
    Point originOne = new Point(23, 94);
    
    originOne now points to a Point object.
    Rectangle rectOne = new Rectangle(originOne, 100, 200);
    
    Now the rectangle's origin variable also points to the Point.

    The Garbage Collector

    Some object-oriented languages require that you keep track of all the objects you create and that you explicitly destroy them when they are no longer needed. Managing memory explicitly is tedious and error-prone. The Java platform allows you to create as many objects as you want (limited, of course, by what your system can handle), and you don't have to worry about destroying them. The Java runtime environment deletes objects when it determines that they are no longer being used. This process is called garbage collection.
    An object is eligible for garbage collection when there are no more references to that object. References that are held in a variable are usually dropped when the variable goes out of scope. Or, you can explicitly drop an object reference by setting the variable to the special value null. Remember that a program can have multiple references to the same object; all references to an object must be dropped before the object is eligible for garbage collection.
    The Java runtime environment has a garbage collector that periodically frees the memory used by objects that are no longer referenced. The garbage collector does its job automatically when it determines that the time is right.

    Returning a Value from a Method

    A method returns to the code that invoked it when it
    • completes all the statements in the method,
    • reaches a return statement, or
    • throws an exception (covered later),
    whichever occurs first.
    Note: You also can use interface names as return types. In this case, the object returned must implement the specified interface.
    // Covariant return type: detail at https://docs.oracle.com/javase/tutorial/java/javaOO/returnvalue.html
    You can override a method and define it to return a subclass of the original method, like this:
    public ImaginaryNumber returnANumber() {
        ...
    }
    
    This technique, called covariant return type, means that the return type is allowed to vary in the same direction as the subclass.

    Using the this Keyword

    Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.

    Using this with a Field

    public class Point {
        public int x = 0;
        public int y = 0;
            
        //constructor
        public Point(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }
    
    

    Using this with a Constructor

    public class Rectangle {
        private int x, y;
        private int width, height;
            
        public Rectangle() {
            this(0, 0, 1, 1);
        }
        public Rectangle(int width, int height) {
            this(0, 0, width, height);
        }
        public Rectangle(int x, int y, int width, int height) {
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
        }
    }
    
    

    Controlling Access to Members of a Class

    • At the top level—public, or package-private (no explicit modifier).
    • At the member level—publicprivateprotected, or package-private (no explicit modifier).
    Access Levels
    ModifierClassPackageSubclassWorld
    publicYYYY
    protectedYYYN
    no modifierYYNN
    privateYNNN
    Classes and Packages of the Example Used to Illustrate Access Levels
    Classes and Packages of the Example Used to Illustrate Access Levels
    Visibility
    ModifierAlphaBetaAlphasubGamma
    publicYYYY
    protectedYYYN
    no modifierYYNN
    privateYNNN

    Understanding Class Members

    Class Variables

        // add a class variable for the
        // number of Bicycle objects instantiated
        private static int numberOfBicycles = 0;
    
    
     // add an instance variable for the object ID
        private int id;
        

    Class Methods

    public static int getNumberOfBicycles() {
        return numberOfBicycles;
    }
    
    
    Not all combinations of instance and class variables and methods are allowed:
    • Instance methods can access instance variables and instance methods directly.
    • Instance methods can access class variables and class methods directly.
    • Class methods can access class variables and class methods directly.
    • Class methods cannot access instance variables or instance methods directly—they must use an object reference. Also, class methods cannot use the this keyword as there is no instance for this to refer to.

    Constants

    The static modifier, in combination with the final modifier, is also used to define constants. The final modifier indicates that the value of this field cannot change.
    For example, the following variable declaration defines a constant named PI, whose value is an approximation of pi (the ratio of the circumference of a circle to its diameter):
    static final double PI = 3.141592653589793;
    

    Initializing Fields

    public class BedAndBreakfast {
    
        // initialize to 10
        public static int capacity = 10;
    
        // initialize to false
        private boolean full = false;
    }
    
    
    
    

    Static Initialization Blocks

    static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Here is an example:
    static {
        // whatever code is needed for initialization goes here
    }
    
    
    

    Initializing Instance Members

    Normally, you would put code to initialize an instance variable in a constructor. There are two alternatives to using a constructor to initialize instance variables: initializer blocks and final methods.
    Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword:
    
    
    {
        // whatever code is needed for initialization goes here
    }
    
    
    
    
    
    The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.
    final method cannot be overridden in a subclass. This is discussed in the lesson on interfaces and inheritance. Here is an example of using a final method for initializing an instance variable:
    class Whatever {
        private varType myVar = initializeInstanceVariable();
            
        protected final varType initializeInstanceVariable() {
    
            // initialization code goes here
        }
    }
    
    
    Quiz:
    Consider the following class:
    public class IdentifyMyParts {
        public static int x = 7;
        public int y = 3;
    } 
    
    1. Question: What are the class variables?
      Answer: x
    2. Question: What are the instance variables?
      Answer: y
    3. Question: What is the output from the following code:
      IdentifyMyParts a = new IdentifyMyParts(); 
      IdentifyMyParts b = new IdentifyMyParts(); 
      a.y = 5; 
      b.y = 6; 
      a.x = 1; 
      b.x = 2; 
      System.out.println("a.y = " + a.y); 
      System.out.println("b.y = " + b.y); 
      System.out.println("a.x = " + a.x); 
      System.out.println("b.x = " + b.x); 
      System.out.println("IdentifyMyParts.x = " + IdentifyMyParts.x);
      
      Answer: Here is the output:
       a.y = 5 
       b.y = 6 
       a.x = 2 
       b.x = 2
       IdentifyMyParts.x = 2
      
      Because x is defined as a public static int in the class IdentifyMyParts, every reference to x will have the value that was last assigned because x is a static variable (and therefore a class variable) shared across all instances of the class. That is, there is only one x: when the value of x changes in any instance it affects the value of x for all instances of IdentifyMyParts.
      This is covered in the Class Variables section of Understanding Instance and Class Members.
    
    
    
    

    No comments:

    Post a Comment

    java special for collection size, array size, and string size

    Size: For Collections (eg: Map, List, etc ): usually it use collection.size(), eg         Map<Character, Integer> map ...