0% found this document useful (0 votes)
19 views33 pages

Refresher: Main Class

Uploaded by

jealianabbysulit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views33 pages

Refresher: Main Class

Uploaded by

jealianabbysulit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

REFRESHER

Monday, 19 August 2024 8:30 am

Main Class
- In creating a project, when the tickbox is checked for main class, ang
lalabas is may name na, name ng bagong class, and may public static
void na.
- Otherwise, wala.

Package
- Para magkasama lahat ng similar utilities

Classes
- Dapat same name ng project and package, dapat it depends sa
functionality
- Do not place java class in the default package

NAMING

Class
- Kapag class, upper case first letter, if 2 or more words, lagi uppercase
first letter.
- Class is a blueprint

Method
- Kapag method, lowercase first letter, if 2 or more words, next word would
be capital.

public static void main(String [] args){


- //main method
- //String is a method
- //PSVM + TAB = shortcut for public static void
- // ung nasa loob nito ang unang magrrun
}

Sa may bond paper na may play button when class is created, it defines
kung main methodd or hindi yung nicreate depending kung tinick box or
hindi

DATA TYPES
1. Primitive
- lowercase
- They are predefined by the language itself and represent basic values
like numbers, characters, and true/false statements
- int, boolean, float, double, char, long

2. Non-primitive
- capital letter

BASICS JAVA Page 1


- capital letter
- can be used to peform certain operations
- they are not objects and don’t have any associated methods.
- String, interger, array, classes, interface

Scanner is a class type

Class type
- may mga methods na iccall

public class declaration (difference sa pagcall ng variables sa public class


and public static void

public static declaration


- declares local variables

main method is static (ano ung static)

main() is public static void for accessibility and to serve as the program's entry
point without returning a value. public ensures that the method is accessible
from outside the class. static method belongs to the class, not an instance of
the class. void indicates that the main() method doesn't return any value.

VARIABLE TYPES
1. Global Variables/Class Variable
- declared inside a class but outsidde a method, have a default value
- String = null, int = 0, double = 0.0, float = 0, long = 0, char =wala
2. Local Variable
- It doesn’t have a default value

import.java.util.* = asterisk means all utils associated with java is called.

ln = line next
print = within the same line

scan.next();
- don't accept white spaces

scan.nextLine();
- accepts white spaces

1 tab = 8 spaces
The main difference between Class and Method is that class is a blueprint or
a template to create objects while method is a function that describes the
behavior of an object.

NAMING RULES (variables, methods, classes)


1. Java allows underscore & dollar sign
2. Don’t use reserved keywords
BASICS JAVA Page 2
1. Java allows underscore & dollar sign
2. Don’t use reserved keywords
3. Must start with small letters
4. Identifiers are case sensitive
5. variables dapat small letters lang

BASICS JAVA Page 3


INTRO TO JAVA
Monday, 19 August 2024 8:31 am

JAVA
- In 1991, SunMicrosystems (acquired by Oracle Corporation on January 27,2010) funded a research project to develop a programming
language that may be used for electronic consumer devices such as television and video cassette recorders.
- The project led by James Gosling resulted in a language called Oak. This was replaced with Java as the latter was already used.
- James Gosling is considered the Father of the Java programming language.
- On May 23, 1995 at Sun World San Francisco, Sun Microsystems, Inc., Java Technology was officially born.
- Java is initially used for developing games.

Java Technology Product Groups:


Java is an object-oriented programming language. It is used to develop a wide range of applications, from cellphones, games development, and webpages to
web servers and e-commerce applications. These applications are built using the following Java technology product groups:
• Java Standard Edition (JSE)
• Java Micro Edition (JME)
• Java Enterprise Edition (JEE)
Each group has its own Software Development Kit(SDK) to develop program for specific device types. The following sections briefly describe the device types
that each group targets.
Java Standard Edition (JSE)
Two types of program may be created; applets and applications. Applets are programs that run within a Web Browser and are used for creating dynamic
and interactive and dynamic pages. Applications run on desktop computers and are used for creating stand-alone programs such as word processors and
games.
Java Micro Edition (JME)
This is used for devices which Java is initially intended for. Games for mobile devices and car navigation systems may be developed using this product group.

Java Enterprise Edition (JEE)

This product group allows the creation of enterprise applications such as e-commerce solutions.

Java Platform Independent


Java is designed to be platform independent. Platform refers to the operating system and the processor used. A Java program compiled in one platform like
Windows could be executed in a machine with Macintosh OS. Unlike other programming languages such as C, a program must be recompiled if run on a
different platform.

JDK (Java Development Kit)


- Allows developers to create Java programs that can be executed by the JRE ( Java Runtime Environment)

IDE (Integrated Development Environment)


- software used to easily code in a certain programming language, has tons of features that make programming easier

Packages
- like a folder in a directory where we can throw all our related codes in the same directory
- lowercase first letter in first word, capital letter first letter in next word

Class

VARIABLES AND DATA TYPES


Variables
- used to store temporary data to be used in our program's runtime.

Data Type
- type of data inside our variable.

1. Characters - holds a single character


2. String - set of characters
3. Boolean - true (1) or false (0)
4. Integers - numeric (byte = - 128 to 127, short, int, long)
5. Floating Point (float = mas marami nasusupport decimal, double = two decimal) - decimal

Identifiers
- name of the variable that the programmer indicated
- used to read and write the variable

Rules of Identifiers
1. can't use any special characters other than underscore and dollar sign.
2. can't use whitespaces
3. can't use numbers alone
4. can use numbers but with letters

Declaring variables
Syntax:
datatype identifier;

BASICS JAVA Page 4


datatype identifier;
datatype identifier = value;

Reassigning Variable
identifier = value;

Printing
System.out.println();
- used to display something

Concatenation
- process of joining strings together with plus operator.
- anything that adds with string is string.
- you can concatenate inside a variable or print statement

Example:
"Hello" + "World";

JavawasoriginallydevelopedoutofSunMicrosystemsplantodevelopaprogramminglanguageforelectronicconsumerdevicelikevideocassetterecorders.

Java Development Kit (JDK) is an application commonly used with a text editor to develop Java programs.

NetBeans may be used to code, compile, and execute java programs. Both can be downloaded for free.

NetBeans like JDK is an Integrated Development Environment where Java programs can be executed.

Java technology Product Groups include Java Standard Edition (JSE), Java Micro Edition (JME), and Java Enterprise Edition (JEE).

Platform Independent is a feature that allows Java programs to run on different operating systems or processors provided that a Java Virtual Machine is available.

BASICS JAVA Page 5


PROGRAMMING BASICS
Monday, 19 August 2024 6:34 pm

A Java program is made up of classes. A class can be thought of as a collection of variables and subroutines (also known as methods). A subroutine is a
collection of program instructions that may be made up of the following essential program elements:
• Literals
• Identifiers
• Expressions
• Statement

Literals
Literals may be thought of as constants or fixed values. They could either be numeric, string or character in general.
Numeric
• literals that are of numeric type. Only the following symbols are allowed {D0,1,2,3….9,+,-,.}

Examples:

Valid Constants: 1, 2.5, 3.6, -1256

Invalid constants:

• 2,345 - Comma(,) is not a valid symbol, it should instead be expressed as 2345.


• 95% - Percent % is not a valid symbol, it should be expressed as 0.95, as % is equivalent to dividing a number by 100.
• (Peso sign) 100 - The peso sign (₱) is not a valid symbol; it should be expressed as 100. (dollar sign is allowed)
String
• literals that are enclosed in double quotation marks (“ “)
Examples: “Hello”, “Green Apple”
Character
• a single character enclosed in single quotation marks (‘ ‘)
Examples: ‘a’, ‘b’, ‘3’
Note: Kung ano lang yung nakalagay sa loob ng quotation, yun lang maiinput so careful.

Identifiers
Identifiers are names given to variables and literals. Literals are constants or fixed values while variables are entities that can hold these literals.

Suppose we have

X=5, 5 is the literal while x is the variable holding the literal value 5.

Identifiers are also used to name sub-programs or methods and class names Methods and class names will become important in the latter chapters. What
is important at this point is how to name variables and literals.

In Java, rules in naming variable are:

A variable name may start with a letter, and underscore (_) or a dollar sign($)
It must not be a keyword, Keywords like if and while have special meaning to java
Subsequent characters may be letters, numbers, underscore or dollar sign.
In following Java’s coding guidelines, the first letter of variable name should be in lowercase. The first letter of the subsequent words should be
capitalized.

Examples: totalBill, grossSales

For literals, identifiers are normally written in uppercase

Ex: PI = 3.1416, DISCOUNT = 0.05

The same rules apply to method and class names, except that class names start with an uppercase letter.

Note: Java is Case Sensitive. It make a distinction between uppercase and lowercase letters. the totalBill variable where in the first letter is in lower case will
be treated differently with TotalBill. The same goes with all identifiers and keywords.

EXPRESSIONS

Expression is a group of elements with operators that determine how they may be evaluated. An expression could either be Arithmetic or a Boolean
expression. An expression either yields a numeric or logical value (i.e. true or false)

ARITHMETIC EXPRESSION

It consists of variables or numeric literals as operands and arithmetic operators


Ex: 5+6
5 and 6 are the operands and + is the operator
Operators:
+, -, *, /, %, ++, – -
The % symbol is the modulus division. It is similar to division except that the remainder is what gets computed.

Unary Operators
The symbols
• ++ Increment (x+1)
• - - Decrement (x-1)
They are called Unary as they only require a single operand
When (++) and (--) are placed before a variable, they are called pre-increment and pre-decrement. On the other hand, if they are placed after the
variable, they are called post-increment and post-decrement.
Example:
int price = 5;
newPrice = ++price
6=6
Both variables have the value of 6 (final/changing value) due to the pre-increment which suggests it to happen.

BASICS JAVA Page 6


int num1 = 10;
int num2 = num1++;
10 = 11
The value of 10 will be stored in the variable num2 while variable num1 will have the value 11 due to the post-increment operator.

int x1 = 5;
int x2 = – - x1;
4=4
Both variables have the value of 4 (final/changing value) due to the pre-decrement which suggests it to happen.

int y1 = 5;
int y2 = y1 - -;
5=4

The value of 5 will be stored in the variable y2 while variable y1 will have the value 4 due to the post-decrement operator.

Post-increment/decrement - assigns the value first into a variable before incrementing/ decrementing it.
Pre-increment/ decrement - increases/decreases the value of the variable prefixed with the unary operators before assigning it to another variable.

Hierarchy of Arithmetic Operators


Parenthesis
/, *, %
+, -
Left to right with the same priority

BOOLEAN EXPRESSION

A boolean expression consists of relational expressions with logical operators. A relation expression consists of operands and relational operators. These
operands may be literals, variables, or even arithmetic expressions. It always yields either true or false value.

Relational Operators

> (greater than)


>= (greater than or equal)
< (less than)
<= (less than or equal)
== (equal)
|= (not equal)

The answer is true only when both expressions are true; otherwise, it is false.

(Multiplication: 1 is True, 0 is False)

The answer is false only when both expressions are false; otherwise, it is true.

(Addition: 1 is True, 0 is False)

The | operator simply negates the result of expression; I True is false and false is true.

Hierarchy of Logical Operators


Parenthesis
I (Not)
&& (And)
|| (Or)
Left to right when evaluating expressions sharing the same operator.

STATEMENTS

BASICS JAVA Page 7


STATEMENTS

These are keywords that perform a predefined task. They are similar to sentences. A sentence as taught in the elementary level is a word or group of
words that expresses a complete thought. A statement in programming is a collection of keywords and elements that expresses a complete instruction. A
sentence ends with a period while a statement in Java ends with a semicolon (;).

Package Declaration:
package javaapplication1;
This line declares that the ‘JavaApplication1’ class is part of the ‘javaapplication1’ package. Packages are used to organize Classes into namespace and
provide a way to manage the class files.
Class Declaration:
public class JavaApplication1 {
This line declares a class named ‘JavaApplication1’. The class is declared as ‘public’, which means it can be accessed from Other classes. This class
contains the ‘main’ method, which serves as the entry point of the program.

Variable Declaration:
String name = "John";
This line declares a String variable names ‘name’ and initializes it with the value “John”. The variable is local to the ‘main’
method, which means it can only be accessed within this method.

Printing a Message:
System.out.println("Hello " + name);
This line prints the concatenated string “Hello” followed by the value of the ‘name’ variable. In this case, it will print
“Hello John” because the ‘name’ variable is initialized with the value “John”.

Understanding the Java Program Structure


A Java program also referred to as an application is made up of one or more classes. These classes may contain variables, Methods, and comments

A java program showing the structure of class:


public class Hello
{
String name = “John”;
//the following method displays Hello John
public static void main(String args[])
{
System.out.println(“Hello ” + name);
}
}

Built-In Packages
- pre-written classes to help the programmer manage input, database.

Import specific class


Syntax: import packagename.classname;

Import whole package


Syntax: import packagename.*;

User Input

String x;
Scanner s = new Scanner(System.in);
x=s.nextLine();

BASICS JAVA Page 8


USING SCANNER
/*
A program that accepts and displays the square of a number using Scanner for keyboard input.
*/
import java.util.Scanner;
public class Square{
public static void main(String args[]){
int num;
int square;
Scanner s = new Scanner(System.in);
num = s.nextInt();
square = num * num;
System.out.printIn(“Squared value:” + square);
}
}

BASICS JAVA Page 9


BASICS JAVA Page 10
CONDITIONAL STATEMENTS
Monday, 19 August 2024 6:47 pm

Conditional Statements
- allows a program to take action based on the given condition.
- compares two values
- decision making
- will run if conditions are true.

RELATIONAL OPERATORS
Equals (==)
Not equals (!=)
Less Than (<)
Less Than or equals (<=)
Greater Thaan (>)
Greater Than or Equals (>=)

IF STATEMENT
- handles 1 conditional expression, it either does something or nothing

Syntax:
if(condition){
//do anything
}

if(age>=18){
System.out.println("LEGAL");
}

IF-ELSE STATEMENT
- handles 2 conditional exprression, it either does the first code block or second

Syntax:
if (condition){
//
}else{

//

IF ELSE IF ELSE STATEMENT


- handles 3 or more conditional expressions
- limitless possibility

Syntax:
if (condition){
//
}else if (condition){
// kahit ilang else if pwede
}else{
// laging nasa dulo
}

NESTED CONDITIONAL STATEMENT


- conditional statement within a conditional statement

BASICS JAVA Page 11


Syntax:

if (condition){
if (condition){
//
}
}

EQUALS FUNCTION
- compare strings more efficiently

Syntax:
String x="Hello";

if (x.equals("Hello")){
//
}

if (x.equalsIgnoreCase("Hello")){
//
}

BASICS JAVA Page 12


SWITCH STATEMENTS
Monday, 19 August 2024 7:13 pm

SWITCH STATEMENTS
- similar to conditional statemenrs but checks for equality and only works with
strings, char, int, and enumerators
- the keyword switch starts the structure and is followed immediately by a test
expression enclosed in parentheses.
- the keyword case is followed by one possible value for the test expression and
a colon.
- the break keyword automatically terminates the switch statements after the
execution of that case.
- the default keyword optionally is used prior to any action that should occur if
the test variable does not match any case.

CASE keyword
- used to define a case in switch statement

Syntax:
switch(variable){

case value1;
//
break;
case value 2;
//
break;
}

DEFAULT Keyword
- handle values that are not on a case
- recommended to use on the end of the switch statement (serves as else
statement)
- di need ng break keyword under

Syntax:
switch(variable){

case value1 (If string "", if int =2;


//
break;
case value 2;
//
break;
default:
Soutprintln("Invalid");
}

BREAK Keyword
- break out of a switch statement or loop without executing the whole block of
code inside it.

BASICS JAVA Page 13


LOOP STATEMENTS
Monday, 19 August 2024 7:36 pm

Loop Control Structure


- Repetitive process until/while a condition is met.

WHILE LOOP
- when u want a code block to run repeatedly while a condition is met.

Syntax:
while(condition){
//
}

ITERATING Arrays
- read every element inside an array and do something
- can be accessed through indeex
- index starts with 0

Array Length
- findd the size of the arrays
- .length();

DO WHILE LOOP
- same as the while loop but executes the code block before checking the condition.

Syntax:
do{
//
}while(condition){
//
}

BREAK Keyword
- break out of a loop earlier than it is expected to end

int i = 0;

while(condition){
// Soutprintln (i);
i++;
break;
}

CONDITIONS IN WHILE LOOP

FOR LOOP
- used when u want a code block to run repeatedly while a condition is met
- more compact format but more complicated version
- used to iterate through collections of arrays

Syntax:
for (intitialization, condition, operation){
//
}

BASICS JAVA Page 14


}

FOR EACH LOOP


- to iterate through collections like arrays easily without knowing the size of the collection.

Syntax:
for (datatype identifier : collection){
//
}

int [] numbers = {1,2,3,4,5}


for (int num : numbers){
Soutprintln(num);
}

Result:
1
2
3
4
5

CONDITIONS IN FOR EACH LOOP

String [] names = {"David", "Alenere", "Abby", "Bene", "ivan"};

for (String name : names){


if (name.equals("Alenere")){
Soutprintln("We found " + namee);
break;

}
}

NESTED FOR LOOP


- for loop inside a loop

BASICS JAVA Page 15


2D ARRAYS
Monday, 19 August 2024 8:24 pm

2D ARRAY
- arrays within an array, rows and columns
- stores one data type at a time

datatype identifiers [][]={


{val1,val2},
{val1,val2},
{val1,val2},
{val1,val2},
}

String users[][]={
{"David","david"},
{"Abby","abby"},
{"bene","Bene"},
{"Ivan","Ivan"},
}

Declaring 2d arrays without values

datatype identifier [][] = new datatype[rows][cols];


String users[][] = new String[4][2];

ITERATING 2D ARRAYS

String users[][]={
//0 //1
//0 {"David","david"},
//1 {"Abby","abby"},
//2 {"bene","Bene"},
//3 {"Ivan","Ivan"},
}

for (int row =0, row < user.length; row++){


for (int col = 0; col <users[row].length;col++){
Soutprintln (users[row][col]);
}
Soutprintln();
}

Result:
David
david

Abby
abby

bene
Bene

Ivan
ivan

BASICS JAVA Page 16


METHODS/ FUNCTIONS
Monday, 19 August 2024 8:49 pm

METHODS/FUNCTIONS
- used to divide and sort functionalities within a class so that the code will be readable even if it is long.

CREATING Methods

Syntax:
modifiers returntype methodName(){
//
}

public static void main(String[] args){


// public - class type
//static - modifier
//void - returntype
//main - methodName
//main method - unang nirurun ng code sa java
}

CALLING Methods
- we need to call other methods to main method

public static void main(String[] args){


sayHello();
}

static void sayHello(){


Soutprintln("Hello");
}

// single line comment

/* multi-line comment */

VARIABLE SCOPING
Global Variables
- are variables declared within a class, it can be accessed within the whole class.
If declaring, it has to have modifier "static".
E.g: static num =100;

Local Variables
- Variables declared inside a method, condition, loops, any other block of code, and only accessible
within that block of code.

Arguments/Parameters
- Value that needs to be passed on a method so that method can use that value and perform various
operations on it.
- U can have as many arguments/parameters as u want. They at as local variable inside a
method/function.

Methods w/Arguments

Modifiers returntype methodName(arguments){

//do anything

BASICS JAVA Page 17


//do anything

Public static void main (String [] args)){

print("hello world");
}

static void print(String word){


Soutprintln(word);
}

Return keyword
- to return a value from the method. used when a method has result.

Return type
- type of the valiue that will be returned, returntype is similar to datatype

void returns nothing


int returns integers
string returns strings and so on

Methods w/ return

Public static void main (String [] args)){


int sum = add(5,2);
Soutprintln (sum);
}

static int add(int num1, int num2 ){


return num1+num2;
}

OVERLOADING Methods
- u can use the same method name but different parameters so that u will cater every possibility of a
method.
- 2 adding numbers and 3 add numbers

Public static void main (String [] args)){

Soutprintln (add(5,2));
Soutprintln (add(5,2,3));

static int add(int num1, int num2 ){


return num1+num2;
}

static int add(int num1, int num2, int num3 ){


return num1+num2 + num3;
}

BASICS JAVA Page 18


PACKAGES AND MODIFIERS
Monday, 26 August 2024 8:23 pm

PACKAGES
- folder in our project where we can throw related codes in the same directory.

Creating packages
- we can create multiple packages in a java project.

Creating classes
- we can create classes inside a package and import it in our main class so that we can use that
class.
- Main class - un lang pinakanagrurun sa code
- subclasses - iniimport sa main class para magamit.

IMPORTING PACKAGES

IMPORT SPECIFIC CLASS


import packagename.classname

IMPORT WHOLE PACKAGE


import packagename.*

CLASS Instantiation
- process of creating an instance of a class so we can use it in our program

className identifier = new ClassName();


Arithmetic a = new arithmetic();

ACCESS MODIFIERS
- used to modify where classes, variables and methods are accessible.
- Keywords kung hanggang saan visibility ng variables, classes and methods
- Ang local variables, hindi pede lagyan ng access modifiers

MODIFIERS (CLASSES)
1. default - the class can only be accessed by classes in the same package.
2. public - the class can be accessed anywhere as long as it is imported.

ACCESS MODIFIERS (METHODS AND VARIABLES)


1. default - accessed by classes in the same package (no keyword needed- normally ginagamit)
Ex: string sam ="2c";, methods, walang public private and protected, normal na ginagawa.
2. public - accessed anywhere as long as it is imported.
3. private - can only be accessed inside its own class
4. protected - can only be accessed by classes in the same package and subclasses.

NON- ACCESS MODIFIERS


- add other functionalities for classes variables, methods, basically used for specific situations
- pwede paghalu-haluin

for class
1. final - the class can't be inherited by other classes.
2. abstract - can't be used to instantiate objects. we can only access an abstract class by
inheriting it from another class.

for methods and variables


1. final - variables cant be reassigned (di pwede imodify) and methods cant be overridden.
2. static - variables/methods belong to class itself rather than its instance. (hindi na need

BASICS JAVA Page 19


2. static - variables/methods belong to class itself rather than its instance. (hindi na need
gumawa ng instance, rekta palit nalang ng number)
3. abstract - can only be used in abstract class methods. does not have a body
4. transient - variables and methods are skipped when serializing object containing them
5. synchronized - methods can only be accessed by one thread at a time
6. volatile - value of an attribute is not cached threadd- locally and is always read from the main
memory.

BASICS JAVA Page 20


CLASSES AND OBJECTS
Monday, 26 August 2024 8:54 pm

OOP
- it focused on implementing real world objects using classes to create variations of objects that
has attributes and purpose.
- it helps create flexible and efficient code than procedural programming.

CLASSES
- created by the programmer, act as a blueprint of an object that u want to implement
- contains attributes and methods that ur desired object should have.

OBJECTS
- created by instantiating a class
- anything that has an attribute and a purpose.
- example: food, person, furniture

ATTRIBUTES
- global variables declared inside the class of our object.
- papalitan lang value nng global variables.
- used to create variations of an objects using one class.

HOW TO USE CLASS USING

CLASS CREATION

modifiers className class{


//attributes
//methods/ purpose
}

PERSON
- first name
- last name
- sex
- age

public Person class {


//attributes
String firstName;
String lastName;
char sex;
int age;
//methods or purpose

CLASS INSTANTIATION
- the process of creating an object using a class so we can use it in our program.

ClassName identifier = new Classname();


Person p = new Person();

ACCESSING ATTRIBUTES

BASICS JAVA Page 21


ClassNAme identifier = new ClassName();

WRITING Attributes
identifier.attribute = value;

READING Attributes
Soutprintln(identifier.attribute);

BASICS JAVA Page 22


CONSTRUCTORS
Monday, 26 August 2024 9:12 pm

CONSTRUCTORS
- it is the method called when u instantiate a class/ create an object.
- to initialize attributes of object or run a block of code when an object is created.

constructor method are named after their classname.

moifiers className class{

className(){
//constructor
}
}

BASICS JAVA Page 23


L1: INTRO TO OOP
Monday, 19 August 2024 8:56 pm

Written Exam and Hands-On exam - week after written exa, lab schedule

PACKAGE
- collection of related classes.

CLASSES
- blueprint kung san nagdedefine data and information/methods related to that
class.

OBJECT
- considered as real world object

CLASS INSTANTIATION/OBJECT REFERENCING


- INSTANCE - dami ng pangyayari
- object referencing, studentt 1 is object referencing the class student.
- no overlapping since maraming instances.
- same data and info from a class but with different values.
- can have multiple instances and di siya mgoverlap.

Student student1= new Student();

Scanner is a class instantiation.

METHOD
- action done by object.
- magbasa ng input.

METHOD W/O ARGUMENT ANDD RETURNING TYPE


- no parameters

VOID - walang returning value

METHOD WITHOUT AN ARGUMENT WITH RETURNING TYPE


- if it has returning type, dapat may return keyword in accordance with return
type.
- pwede gamitin sa operators and directly sa output

METHOD WITH ARGUMENT AND W/O RETURNING TYPE


- BAWAL SA OPERATORS AND DIRECTLY SA OUTPUT

METHOD WITH ARGUMENT AND RETURNING TYPE

String sayHello(){
return "hello";
}

PARAMETER - variable name


ARGUMENT - actual value of the parameters

5 MIN PRESENTATION
- user input
- 2 objects, data na need coming from user

OOP 1 Page 24
- 2 objects, data na need coming from user
- 2 class, different methods

E- raising to number of exponents

Decimal Format:
W % in decimal format "0.00%" - multiplied to 100 + %

Random Class:
Automatically generate a random number, mula sa range ng integer whether
positive or negative.

(10)- boundary of number

OOP 1 Page 25
L2: PACKAGES AND CLASSES
Thursday, 12 September 2024 2:08 pm

PACKAGES
- folder in our project where we can throw related codes in the same directory.
- Collection of related classes.

Creating packages
- we can create multiple packages in a java project.

Creating classes
- we can create classes inside a package and import it in our main class so that
we can use that class.
- Main class - un lang pinakanagrurun sa code
- subclasses - iniimport sa main class para magamit.

IMPORTING PACKAGES

IMPORT SPECIFIC CLASS


import packagename.classname

IMPORT WHOLE PACKAGE


import packagename.*

CLASS Instantiation or Object Referencing


- process of creating an instance of a class so we can use it in our program

className identifier = new ClassName();


Arithmetic a = new Arithmetic();

ACCESS MODIFIERS
- used to modify where classes, variables and methods are accessible.
- Keywords kung hanggang saan visibility ng variables, classes and methods
- Ang local variables, hindi pede lagyan ng access modifiers

MODIFIERS (CLASSES)
1. default - the class can only be accessed by classes in the same package.
2. public - the class can be accessed anywhere as long as it is imported.

ACCESS MODIFIERS (METHODS AND VARIABLES)


1. default - accessed by classes in the same package (no keyword needed-
normally ginagamit)
Ex: string sam ="2c";, methods, walang public private and protected, normal na
ginagawa. FRIENDS

2. public - accessed anywhere (within Java) as long as it is imported. PUBLIC


3. private - can only be accessed inside its own class (kahit same pa ng
package). ONLY ME (ITS ONLY CLASS)
Encapsulation - hiding of information
4. protected - can only be accessed by classes in the same package and
subclasses (child class) super class(parent) . For inheritance . Kahit
magkaibang package kung subclass nung pinaglalagyan na class na
pinaglalagyan nung variables or methods na un pwede un)

NON- ACCESS MODIFIERS

OOP 1 Page 26
NON- ACCESS MODIFIERS
- add other functionalities for classes variables, methods, basically used for
specific situations
- pwede paghalu-haluin access and non-access modifiers, huwag lang yung
dalawang access modifiers sa isang method, pero 2 non-access pwede.
- Keywords that gives aditional meaning or functions to variables and methods
- Cant be added to local variables, for global only

/* not yet discussed


for class
1. final - the class can't be inherited by other classes.
2. abstract - can't be used to instantiate objects. we can only access an abstract
class by inheriting it from another class.
*/

for methods and variables


1. final - variables cant be reassigned (di pwede imodify) and methods cant be
overridden.
Final/constant variable: values are unchangeable, hindi pwedeng walang
declared values. Pwede ka lang maglagay value through initialization or
constructor.
2. static - variables/methods belong to class itself rather than its instance. (hindi
na need gumawa ng instance, rekta palit nalang ng number)
Static variables/class variables: ONE COPY of variables only unlike instance
variables na pwede maraming instances. Medyo italic.
Instance variables: More than one copy, each object has their copy of
instances. Normal letter

/* not yet discussed


1. abstract - can only be used in abstract class methods. does not have a body
2. transient - variables and methods are skipped when serializing object
containing them
3. synchronized - methods can only be accessed by one thread at a time
4. volatile - value of an attribute is not cached threadd- locally and is always read
from the main memory.
*/

3 TYPES OF GLOBAL VARIABLES


Final/constant variable: values are unchangeable.
Static variables/class variables: ONE COPY of variables only unlike instance variables
na pwede maraming instances. Medyo italic.
Proper calling: classname.variable = "Abby"; // If not in the same class
Candidates.age;
Instance variables: More than one copy, each object has their copy of instances.
Normal letter

Constructor = this (refers to class).name


Kapag static bawal tawagin this, bawal un kasi isang value lang naman mababato
This keyword cant be used to static methods.

Kung may local and global na same name pero gusto mo tawagin is global, call the
(classname.variable), uunahin kuhanin is local variable in short ibahin pangalan

To use instane variables to static methods, gawa class instantiation and objects
Di pwede tawagin instance variables directly sa static methods

OOP 1 Page 27
L3: ENCAPSULATION
Thursday, 19 September 2024 1:13 pm

Encapsulation: It is the process of hiding all the details of how a piece of software is
written and telling only what a programmer needs to know. Inside the "capsule" (can
be a class or interface). Encapsulation may hide the fine details. For this reason, it is
often called information hiding.

• Inside a capsule (capsule - can be a class or interface)


• REMINDER: it is recommended that instance variables are declared with private
(most restricted modifier) access modifiers in Encapsulation
• Private - data are kept in a capsule/its own class

We set the arguments the same, andd same sequence sa constructor;

OOP 1 Page 28
L4: METHOD OVERLOADING
Tuesday, 24 September 2024 8:14 am

Bawal talaga gumawa ng same method but it is possible with method overloding

Method overloading : we can overload the same method name but list of the
parameters must be different.

FIRST RULE: LIST MUST BE DIFFERENT

(string first name)


String address

They are both string, di sila different

AMBIGUOUS METHOD OVERLOADING


- int/double : double can accept whole numbers
There's a tendency na isang method di mabasa
A whole number can be accepted by int, double, and float, kapag di nakaspecifty
decimal places

SECOND RULE: method with same name but different returning value (also list must
be different)

Just changing the returning type is insufficient, list must be also different

OOP 1 Page 29
L5: CONSTRUCTOR
Tuesday, 24 September 2024 8:32 am

CONSTRUCTOR: specialized method because may rules

Is consider object method


Walang modifier and returntype

RULE 1; The name of constructor must be the EXACTLY same after class name (kung
lowercase lowercase, kung uppercase, uppercase)
It is executed after the keyword new
Through the use, u can initialize directly their calue
Through c, u can set the value

RULE 2: Ang mga constructor walang returning type


CONSTRUCTOR OVERLOADING

Final, pwede initialize pero dapat sa lahat ng methods nakalagay value, kahit
magkaiba iba pa

Static - isa lang

Atleast 2 constructors, 3 methods (1 with returning type);

OOP 1 Page 30
OBJECT METHODS
Wednesday, 25 September 2024 7:26 pm

Method: declared inside an object class, considered as object's purpose

OOP 1 Page 31
L6: INHERITANCE
Wednesday, 2 October 2024 3:39 pm

INHERITANCE: namamana, parent class pnamamana yung kanilang attributes,


fields, variables by child classes. Ano man katangian ng parent class, mamamana
ng subclass.
- an oop technique to inherit attributes and methods from one class to another for
code reusability.
(2 or more class na nag iinherit ssa isa pang class)

Inherited: parent class/superclass/ basee class


Inherit: child class/subclass/ derived class

• Sa inheritance, mas nagiging reusable yung attributes, if they have the same
attributes and methods

• Kung ano yung attribute ng subclass di mamamana ng parent class.

• Code reusability beneficial ang inheritance

EXTENDS Keyword
- used after class name and it indicates that thhe certain class will inherit from
another class.
- nagagawa inheritance

Every time u are creating a variable, it consumes a space in the memory

Protected access modifier: its accessibility is within the same package and its
subclasses

Mas maraming kayang gawin ang subclass kaysa kay superclass. Yung pinakalast
na nagmana dhil nakuha nya lahat ng ininherit if multilevel.

Kayang mag instantiaate using parent class for the subclass pero di pwede
viceversa

Ex: Car d = new Motor(); *parameters must be based on the parameters of the
subclass

Single inheritance: nagiinherit lang sa isang class.

Hierarchical Inhertance: Class D, Class B, and Class C nag iinherit kay Class A.

Multilevel Inheritance: Class C extends Class B, Class B extends Class A. namamana


ni class c attributes ni A since nageextend si B kay A. There's multiple inheritance
through INTERFACES, no multiple inheritance kapag class ginagamit like ginagawa
natin.

If u created a constructor walang laman and parameters, wala error

If u created a constructor with parameters, it must be present also in the subclasses


or else there would be an error

Hindi naiinherit constructor, but we can invoke by using super keyword

OOP 1 Page 32
Hindi naiinherit constructor, but we can invoke by using super keyword
Kapag default access modifier, wala problem

Kapag protected - symbol is may key


Kapag default - package symbol

Super- for invoking the constructor from the parent class, dito nagseset value, same
with keyword this in terms of, di sila pede gamitin parehas sa mga may keyword na
static.

In inheritance,
This keyword- pertains to the subclasses and parent class

METHOD OVERRIDING: naababago, binabago whatever meron sa print method


- to retain the functonality from the super class use the superclass w/the
methodName

Kung ano returning type sa parent class, yun din sa subclass


Kung ano parameter, un din
Kung ano methodname, un din
Hgindi pwedeng less restrictive ung sa subclass
It is also polymorphism, runtime polymorphism (one method, can do different
action)

Method overloading overriding are both polymorphism.

Overloading: Compile time polymorphism.


The term method overloading allows us to have more than one method with the
same name. Since this process is executed during compile time, that's why it is
known as Compile-Time Polymorphism.

Overriding: Runtime polymorphism


Runtime polymorphism, also known as the Dynamic Method Dispatch, is a process
that resolves a call to an overridden method at runtime. The process involves the use
of the reference variable of a superclass to call for an overridden method.

Subclass must not be less restrictive pero kapag e.g parent class is protected tas
subclass is public pwede un since less restrictive un

Kapag may keyword na private , di siya namamana ng mga subclasses

POLYMORPHISM: poly means many and morph takes different forms


Isang class maraming variant.
OOP technique that utilizes inheritance to create 1 class and make several classes
inherit from that class so it can take many forms.

OOP 1 Page 33

You might also like