CoreJava - Chapter 4: Objects and Classes

Introduction to Object-Oritented Programming

  • Introduction
    • Each object has a specific functionality, exposed to its users, and a hidden implementation
    • Basically, as long as an object satisfies your specifications, you don't care how the functionality is implemented
    • OOP vs Procedural Programming
      • for procedural programming, Algorithms + Data Structures = Program. Algorithms come first
      • for OOP, we put the data first, then looks at the algorihtms to operate on the data
    • OOP is more appropriate for larger programs
  • Classes
    • A class is the template or blue print from which objects are made
    • When you construct an object from a class, you are said to have crated an instance of the class
    • Encapsulation (information hiding)
      • combining data and behavior in one package and hiding implementation details from the users of the object
      • instance fields
      • methods
      • the key is to have methods never directly access instance fields in a class other than their own. Programs should interact with object data only through the object's methods
    • Cosmic super class - Object
    • Inheritance
  • Objects
    • Three key characteristics
      • behavior: what can you do with this object, or what methos can you apply to it?
      • state: how does the object react when you invoke those methods? 
      • identity: how is the object distinguisehd from others that may have the same behavior and state?
        • individual objects that are instances of a class always differ in their identity and usually differ in their state
  • Identifying classes
  • Relationship between classes
    • Dependence ("uses-a")
      • Try to minimize the number of classes that depend on each other - minimize the coupling between clsses
    • Aggregation("has-a")
    • Inheritance("is-a")
    • UML notations
      • A -> B: A is a child class of B

Using Predefined Classes

  • Objects and Object Variables
    • Constructors 
      • new keyword
    • Object vs Object variables
      • Date deadline

        defines an object variable, deadline, that can refer to objects of type Date. It is important to realize that the variable deadline is not an object and, in fact, deos not even refer to an object yet

      • It is important to realize that an object variable doesn't actually contain an object. It only refers to an object

      • In Java, the value of any object variable is a reference to an object that is storedelsewhere. The return value of the new operator is also a reference

      • Date deadline = new Date();

        The above sattement has two parts. The expression new Date() makes an object of type Date, and its value is a reference to that newly crated object. That reference is then stored in the deadline variable

      • You can explicitly set an object variable to null to indicate that it currentlyrefers to no object

      • Java object variables are similar to C++ references

      • All Java objects live on the heap. When an object contains another object variable, it contains just a pointer to yet another heap object 

    • The LocalDate Class of the Java Library

      • The library designers decided to separate the concenrs of keeping time and attaching names to points in time. Therefore, the standard Java library contains two separte classes: the Date class, which represents a point in time, and the LocalDate class, which expresses days in the familiar calendar notation

      • You do not use a constructor to construct objects of the LocalDate class. Instead, use static factory methods that call constructors on your behalf

        • LocalDate.now()
          
          LocalDate newYearsEve = LocalDate.of(1999, 12, 31);
          
          int year = newYearsEve.getYear(); // 1999
          int month = newYearsEve.getMonthValue(); // 12
          int day = newYearsEve.getDayOfMonth(); // 31
          
          LocalDate aThousandDaysLater = newYearsEve.plusDays(1000);
          
          year = aThousandDaysLater.getYear(); // 2002
          month = aThousandDaysLater.getMonthValue(); // 09
          day = aThousandDaysLater.getDayOfMonth(); // 26

           

  • Mutator and Accessor Methods
    • After invoking the method on an object, the state of the object changes
    • In contrast, methos that only access objects without modifying them are sometimes called accessor methods

 

Defining Your Own Classes

  • An Employee Class
    • class definition example
      • class ClassName {
            field1
            field2
            ...
            constructor1
            constructor2
            ...
            method1
            method2
            ...
        }

         

      • Given that the example program consists of two classes: the Employee class and a class EmployeeTest with the public access specifier, the main method is contained in the EmployeeTest class, and the name of the source file is EmployeeTest.java because the name of the file must match the name of the public class

      • You can only have one public class in a source file, but you can have any number of nonpublic classes

      • Nextm when you compile this source code, the compiler creates two clas files in the directory: EmployeeTest.class and Employee.class

      • You then start the program by giving the bytecode interpreter the name of the class that contains the main method of your program

  • Use of Multiple Source Files

    • If you put different classes into different java files, you can invoke the Java compiler with a wildcard:

      • javac Employee*.java
        //or 
        javac EmployeeTest.java

        When the compiler sees the Employee class being used inside EmployeeTEst,java, it will look for a file named Emloyee.class. If it does not find that file, it automatically searches for Employee.java nd compiles it

  • Constructors

    • A constructor has the same name as the class

    • A class can have more than one constructor

    • A constructor can take zero, one, or more parameters

    • A constructor has no return value

    • A constructor is always called with the new operator

    • All Java objects are constructed on the head and that a constructor must be combined with new

    • Note that do not declare local variables inside a constructor, which is only accessible inside the constructor

  • Declaring Local Variables with var

    • As of Java 10, you can declare local variables with the var keyword instead of specifiying hteir type, provided their type can be inferred from the initial value

  • Working with null References

    • Permissive approach

      • turn a null argument into an appropriate non-null value

    • Tough approach

      • reject a null argument

        • Objects.requireNonNull(n, "the name cannot be null");

           

  • Implicit and Explicit Parameters

    • public void raiseSalary(double byPercent)
      {
          double raise = this.salary * byPercent / 100;
          this.salary += raise;
      }
      
      // number007.raiseSalary(5);

      The raiseSalary method has two parameters. The first parrameter, called the implicit parameter, is the object of type Employee that appears before the method name. The second parameter, the number inside the parentheses after the method name, is an explicit parameter

    • In every method, the keyword this refers to the implicit parameter

  • Benefits of Encapsulation

    •  If you want to get and set the value of an instance field, then you need to supply three items

      • A private data field

      • A public field accessor method; and

        • Be careful not to write accessor methods that returm references to mutatble objects, because this will lead to the break of encapsulation (the returned reference and the private field refer to the same mutable object)

        • If you need to return a reference to a mutable object, you should clone it first. A clone is an exact copy of an object stored in a new location

      • A public field mutator method

    • Benefits

      • You can change hte internal implementation without affecting any code other than the methods of the class

      • Mutator methods can perform error checking

  • Class-Based Acess Privileges

    • A method of an object class is permitted to acess the private fields of any object of the same type

      • class Employee
        {
        . . .
            public boolean equals(Employee other)
            {
                return name.equals(other.name);
            }
        }

         

  • Private Methods

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值