310 likes | 508 Vues
Java Classes. A Java program consists of a set of class definitions, optionally grouped into packages. Each class encapsulates state and behavior appropriate to whatever the class models in the real world and may dictate access privileges of its members.
E N D
A Java program consists of a set of class definitions, optionally grouped into packages. • Each class encapsulates state and behavior appropriate to whatever the class models in the real world and may dictate access privileges of its members. • In programming system: encapsulation, data hiding, polymorphism, and inheritance.
Classes Minimally, a class defines a collection of state variables, as well as the functionality for working with these variables. The syntax for defining a class is straightforward: class ClassName { variables methods } For example, an Employee class might resemble: class Employee { String name; ... }
Methods • In Java, methods must be defined within the class definition. The general syntax for methods is: ReturnTypeName methodName(argument-list) { body } where ReturnTypeName can be a primitive type, a class, or an array. All methods must specify a return type, even if it is void (indicating no return value). Some of the most common methods are so-called getter/setter accessor methods that provide controlled access to the state of an object. For example, consider the following simple employee record definition: class Employee { String name = null; void setName(String n) { name = n; } String getName() { return name; } }
Constructors are optional Java constructors are methods that have the same name as the enclosing class and no return type specifier. The formal argument list of the constructor must match the actual argument list used in any new expression. To be able to execute: Employee e = new Employee("Jim"); you must specify a constructor in Employee: class Employee { String name = null; public Employee(String n) { name = n; } ... }
Inheritance Java supports the single inheritance model, which means that a new Java class can be designed that incorporates, or inherits, state variables and functionality from one existing class. The existing class is called the superclass and the new class is called the subclass. Specify inheritance with the extends keyword. For example, to define a manager as it differs from an employee: you would write the following: class Manager extends Employee { ... } The Manager subclass inherits all of the state and behavior of the Employee superclass Subclasses may also add data or method members: class Manager extends Employee { intparkingSpot; void giveRaiseTo(Employee e) {...} }
Access rights Data hiding is an important feature of object-oriented programming that prevents other programmers (or yourself) from accessing implementation details of a class. The two most common class member access modifiers are public and private. Any member modified with public implies that any method in any class may access that member. Conversely, any member modified with private implies that only methods of the current class may refer to that member (even subclasses are denied access). In general, it is up to the programmer to determine the appropriate level of visibility, but there are a few reasonable guidelines: • constructors are public so other classes can instantiate them. • data members (state/attribute) should be private, forcing access through public getter/setter • A public member is visible to any other class. A private member is only visible within the defining class.
Encapsulation Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. public class Bicycle { private int cadence; private int gear; private int speed; public intgetCadence(){ return cadence; } public void setCadence(intnewValue){ cadence = new value; } ………..(getters and setters for all fields) }
Polymorphism Polymorphism is the ability to create a variable, a function, or an object that has more than one form. public class Animal { public void makeNoise() { System.out.println("Some sound"); } } class Dog extends Animal{ public void makeNoise() { System.out.println("Bark"); } } class Cat extends Animal{ public void makeNoise() { System.out.println("Meow"); } }
public class Demo { public static void main(String[] args) { Animal a1 = new Cat(); a1.makeNoise(); //Prints Meowoo Animal a2 = new Dog(); a2.makeNoise(); //Prints Bark } }
Examples: boolean passCourse = “true”; char myFirstInitial = ‘k’; byte numOfChildren = 8; short tripMiles = 1532; int carMileage = 51357; long creditCardNum = 45656778222643299L; float floatNumExmaple = 32.32F; double doubleNumExample = 45.34;
Math operators • Add + • Subtract - • Multiply * • Divide / • Modulus % (modulus is the remainder value of a divided number) • To increment by one ++ • To decrement by one --
Increment examples • Increment prefix example: int a = 0; int b = 0; a = ++b; a = 1 and b is = 1 • Increment postfix example: int a = 0; int b =0; a = b++; a = 0 and b = 1
println() System.out.println(); System is a Java class out is a PrintStream in the System class println is a method of the PrintStream class The function of this line of code is to print output to a screen.
java.lang.String class A simple String can be created using a string literal enclosed inside double quotes as shown; String str1 = “My name is bob”; We can concatenate Strings as follows: String stri = “My name” + “is bob”; The String class has many methods that we will explore deeper into the course.
Constants • A constant in Java is used to map an exact and unchanging value to a variable name. • Constants are used in programming to make code a bit more robust and human readable. • When you declare a variable to be final we are telling Java that we will NOT allow the variable’s value to be changed. • Using private allows this constant to only be used in the class it is created in. You would make it public if you wanted other classes to access it. The static keyword is to allow the value of the constant to be shared amongst all instances of an object. As it's the same value for every object created it only needs to have one instance private static final int NUMBER_OF_HOURS_IN_A_DAY = 24;
/* Discrete Mathematics Lab * Author: last names of your lab group * Class: CSCI 130 * Topic: Lab 2 Shapes * / Import java.io.*; Import csci130.*; class Shape{ private String shapeDescription; public String getShapeDescription(){ return shapeDescription; } public void setShapeDescription(String description){ shapeDescription = description; } } class Lab2 { public static void main(String args[]) { Shape myShape = new Shape(); myShape .setShapeDescription(“square”); System.out.println(“Shape is set to “ + myShape.getShapeDescription()); } } //Output: Shape is set to square
Imports • An import statement is a way of making more of the functionality of Java available to your program. Java has its classes divided into "packages." You only import to Java packages you are going to use. You can look at the Java API at this url: http://docs.oracle.com/javase/6/docs/api/ • API means Application Programming Interface. An API is the interface implemented by an application which allows other applications to communicate with it.
Refactoring • Refactoring is improving the design of exiting code without changing its behavior.
ISA Relationship • Where one class is a subclass of another class. public class Animal { public void makeNoise() { System.out.println("Some sound"); } } class Dog extends Animal{ public void makeNoise() { System.out.println("Bark"); } } The Dog class is a subclass of the Animal class. A dog is an (ISA) animal. • Overriding: When a subclass has a method with the same signature as its superclass and has the ability to define a behavior that is specific to the subclass. • Signature: the name of the method and the inputs. In the above example makeNoise() is the signature. The method could be overidden with different inputs.
Casting Primitives • In programming, type casting is the process of "casting" a value of a certain data type, into a storage variable that was designed to store a differentdata type. Casting here mean the conversion of that value to another version that could fit the variable of the different data type. Type casting in certaincases could lead to loss of information, loss of precision and errors, if not performed carefully. • To type cast a value into a certain variable, we use the assignment operator, and assign the variable with the value to be type-casted, preceded bythe type we are type casting into. int x = 13; double y = (double)x; // here we type cast the value 13, to a double System.out.println("value of x : "+x); // 13 System.out.println("value of y : "+y); // 13.0
Example double x = 13.4; //int y = x; // if we use this, a "loss of precision" error will occur int y = (int)x; //type casting x to an int , type casting floating points to integers is necessary System.out.println("value of x : "+x); • System.out.println("value of y : "+y); • value of x : 13.4 • value of y : 13
Constructors • A class can contain zero to many constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations—except that they use the name of the class and have no return type. For example, Bicycle has one constructor: public Bicycle(intstartCadence, intstartSpeed, intstartGear) { gear = startGear; cadence = startCadence; speed = startSpeed; } To create a new Bicycle object called myBike, a constructor is called by the new operator: Bicycle myBike = new Bicycle(30, 0, 8); new Bicycle(30, 0, 8) creates space in memory for the object and initializes its fields. The compiler automatically provides a no-argument, default constructor for any class without constructors
Java truth table symbols & is and && is and | is or || is or ! is not
Short Circuiting • The && and || operators "short-circuit", meaning they don't evaluate the right hand side if it isn't necessary. • The & and | operators, when used as logical operators, always evaluate both sides. • There is only one case of short-circuiting for each operator, and they are: false && ... - it is not necessary to know what the right hand side is, the result must be false true || ... - it is not necessary to know what the right hand side is, the result must be true