Follow
Publications: 65 | Followers: 0

Java Classes - Heartland Community College

Publish on Category: Birds 0

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.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 fordefining a class is straightforward:classClassName{variablesmethods}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:ReturnTypeNamemethodName(argument-list) {body}whereReturnTypeNamecan 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/setteraccessormethods that provide controlled access to the state of an object. For example, consider thefollowing simple employee record definition:class Employee {String name = null;voidsetName(String n) {name = n;}StringgetName() {return name;}}
Constructors are optional
Java constructors are methods that have the same name as the enclosing class and no return typespecifier.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 fromone existing class. The existing class is called thesuperclassand the new class iscalled thesubclass. 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 EmployeesuperclassSubclasses may also add data or method members:class Manager extends Employee {intparkingSpot;voidgiveRaiseTo(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 mayaccess that member. Conversely, any member modified with private implies thatonly methods of the current class may refer to that member (even subclasses aredenied access).In general, it is up to the programmer to determine the appropriate level ofvisibility, 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/setterA public member is visible to any other class. A private member is only visible within the defining class.
Encapsulation
Encapsulationis 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 {privateintcadence;privateintgear;privateintspeed;publicintgetCadence(){return cadence;}public voidsetCadence(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 voidmakeNoise(){System.out.println("Some sound");}}class Dog extends Animal{public voidmakeNoise(){System.out.println("Bark");}}class Cat extends Animal{public voidmakeNoise(){System.out.println("Meow");}}
public class Demo{public static void main(String[]args) {Animal a1 = new Cat();a1.makeNoise(); //PrintsMeowooAnimal a2 = new Dog();a2.makeNoise(); //Prints Bark}}
8 Primitive Data Types
Examples:
booleanpassCourse= “true”;charmyFirstInitial= ‘k’;bytenumOfChildren= 8;shorttripMiles= 1532;intcarMileage= 51357;longcreditCardNum= 45656778222643299L;floatfloatNumExmaple= 32.32F;doubledoubleNumExample= 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:inta = 0;intb = 0;a = ++b;a = 1 and b is = 1Increment postfix example:inta = 0;intb =0;a = b++;a = 0 and b = 1
println()
System.out.println();System is a Java classout is aPrintStreamin the System classprintlnis a method of thePrintStreamclassThe function of this line of code is to print output to a screen.
java.lang.Stringclass
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:Stringstri= “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 instanceprivate static finalintNUMBER_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 StringshapeDescription;public StringgetShapeDescription(){returnshapeDescription;}public voidsetShapeDescription(String description){shapeDescription= description;}}class Lab2 {public static void main(Stringargs[]) {ShapemyShape= 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 thisurl:http://docs.oracle.com/javase/6/docs/api/API meansApplicationProgrammingInterface. 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 voidmakeNoise(){System.out.println("Some sound");}}class Dog extends Animal{public voidmakeNoise(){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 itssuperclassand 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 examplemakeNoise() is the signature. The method could beoveriddenwith 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.intx = 13;doubley = (double)x; // here we type cast the value 13, to a doubleSystem.out.println("value of x : "+x); // 13System.out.println("value of y : "+y); // 13.0
Example
doublex = 13.4;//inty = x; // if we use this, a "loss of precision" error will occurinty = (int)x; //type casting x to anint, type casting floating points to integers is necessarySystem.out.println("value of x : "+x);System.out.println("value of y : "+y);value of x : 13.4value of y : 13
Constructors
A classcan contain zero to many constructorsthat 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:publicBicycle(intstartCadence,intstartSpeed,intstartGear) {gear=startGear;cadence =startCadence;speed =startSpeed;}Tocreate a new Bicycle object calledmyBike, a constructor is called by the new operator:BicyclemyBike= new Bicycle(30, 0, 8);newBicycle(30, 0, 8) creates space in memory for the object and initializes its fields.Thecompiler automatically provides a no-argument, default constructor for any class withoutconstructors
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 falsetrue|| ... - it is not necessary to know what the right hand side is, the result must betrue

0

Embed

Share

Upload

Make amazing presentation for free
Java Classes - Heartland Community College