Object Oriented Programming / Java

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

How do you call the constructor?

dThe constructor is called automatically when an object is instantiated using the new keyword. For example: Dog fido = new Dog();

What's the command to execute Java bytecode?

java filename

What's the command to compile Java source code?

javac filename.java

What does the access modifier private mean?

private means our variable or method is only accessible within the same class.

What does the access modifier public mean?

public means our variable or method is visible to any class in our project.

What is abstraction?

(In terms of OOP, abstraction is the concealment of low-level implementation details and displaying only the functionality to the user. It achieves this concealment by centralizing common characteristics and by generalizing behavior into classes. For example, we can take the sum of all cars and abstract away common characteristics. Cars have: - wheels - steering wheel - engine or motor - pedals By the same token, we can take the sum of all cars and generalize behavior. Cars can: - drive forward - reverse - brake - honk In short, abstraction allows you to focus on what something does, not how it does it. Abstraction allows only essential details to be shown to the user by hiding internal details. Another way to think about it is, we are only focused on the input and the output - not what's in-between. --------------------------------------- The difference between encapsulation and abstraction is that abstraction focuses on hiding complexity, whereas encapsulation focuses on hiding data.

What are the restrictions of static methods?

- A static method can only call other static methods. - A static method must only access static data. - A static method cannot reference to the current object using keywords super or this.

What are the different levels of scope in Java?

- Class scope A variable declared directly in a class is accessible throughout the class, including methods in the same class. - Local scope (inside a method) A variable declared inside a method is known as a local variable. This means it's only accessible within the method it was declared in. - Block scope Variables declared inside a code block are known as block-level variables. This includes variables declared in if-else blocks, switch statements, and loops.

What are three different control flow constructs?

- Sequences / Sequential flow - Branching / Conditional flow - Looping / Repetitive flow

What are the similarities between all loops?

- They have a condition that evaluates to a boolean value - They have a block of code that's executed when the condition is met - There needs to be an update expression, a statement that updates the value used in the condition

What are the general rules for if-else statements?

- an if can exist without an else - an else cannot exist without an if - else blocks do not use conditions - we execute a block of code if the condition is true

What are the four keywords of switch statements?

- switch - case - break (resumes code execution, exists switch) - default (provides the fall-back condition)

What's the file extension for Java bytecode?

.class

What's the file extension for Java source code?

.java

What are the four pillars/foundational concepts of OOP?

1. Encapsulation 2. Abstraction 3. Inheritance 4. Polymorphism

What are two examples of polymorphism?

1. Method overriding, which is an example of run-time polymorphism 2. Method overloading, which is an example of compile-time polymorphism

What are the three uses for super?

1. super() can be used to invoke the immediate parent class constructor 2. super can be used to refer to the immediate parent class so that we can invoke one of its methods. (since a child inherits its parent's methods, this isn't strictly necessary) 3. super can be used to refer to the immediate parent class so that we can access one of its instance variables While not necessary, using super.propertyName will make it explicit you wish to refer to an attribute on the parent class. It will be necessary if you have a property of the same name in the child class but wish to access the property from the parent class.

What is a binary operator?

A binary operator is an operator that performs an operation on two operands. Examples: + - * / (truncating division) // (regular division) && (and) || (or) != (not equal)

What is branching / conditional flow?

A branching/conditional structure provides different pathways for code to execute, depending on the result of some conditions, which result in boolean values.

What is a class?

A class is most typically used as a template/blueprint that represents a single concept from which objects are modeled after. Classes contains state (instance variables) and behavior (methods). You can also use a class to host static methods, meaning the class has functions that are able to be called directly, i.e. you do not need to instantiate objects in order to use them. Classes are typically created in their own file. In such cases, the class name must match the file's name.

What is a class member?

A class member is just a variable or method that is inside of a class.

When is a constructor called?

A constructor is called when we instantiate an object via the new keyword.

What is a for loop?

A for loop allows the repetition of a block of code for each element in a collection.

What is looping / repetitive flow?

A looping structure allows the repetition of a block of code. There are two types of looping structures: 1. while loops 2. for loops

What is a method?

A method is a function implemented by a class

What is a method signature?

A method signature are the keywords associated with a method declaration. A method signature includes: - the access modifier - the return type - the method name - the parameters

What is a parameterized constructor?

A parameterized constructor is just a constructor that takes in values as arguments. This means that objects instantiated from the same class will possess different attributes because objects will be built based on the arguments we pass into the constructor. - A constructor must have the same name as the class - Constructors do not have a return type - Must be public (otherwise it can't be called)

What is upcasting?

A process of casting a class subtype to a super type, for example: going from String to Object or from the Manager class to the employee class Permitting an object of a subclass type to be treated as an object of any superclass type (Or going from int to double with data types)

What is a reference variable?

A reference variable stores the memory address of an object. Therefore, we say that the variable "refers" to the object. The variable's data type is that of the object we're trying to make (the class name).

What must be the first line of any constructor?

A super() or this() call must be the first line of any constructor.

What is a unary operator?

A unary operator is an operator that performs an operation on one operand. Examples: ! (negates the value of a boolean value) ++ (increase value by 1) -- (decrease value by 1) ** (exponentiation)

What is a while loop?

A while loop allows the repetition of a block of code while a given condition is true. In other words, the block of code is repeated until the condition becomes false.

What is a while loop?

A while loop is used to repeat a block of code until a condition is no longer true, i.e. until a condition becomes false. If the condition is perpetually true, that is known as an infinite loop, because it will repeat forever.

What's the benefit of abstraction?

Abstraction of low-level implementation details creates a simpler interface. This is true for programming as well as real-world objects such as cars or computers. Another benefit is a reduced impact of change. This means that as long as the inputs and the outputs of a class are the same, we can rewrite the class and there will be no impact to the application. (i.e. code is more modular)

What are arrays?

An array is a data structure which contains multiple elements. In Java, an array must hold only one type of element. Arrays are also fixed in size in Java, and are considered an Object.

What is an operand?

An operand is a value which an operator acts upon. For example, in the expression 3 + 5 the operands are 3 and 5

What are annotations?

Annotations are modifiers that can be applied to classes, variables or methods, which provide meta-data context for the entity. For example: @Override public void printAnimalInfo() { System.out.println("I am a Reptile"); }

Which methods or properties can a subclass not inherit?

Any variables or methods that are private in the superclass cannot be inherited.

What do access modifiers do?

As the name implies, access modifiers help restrict the scope of a class, constructor, variable, method, or data member.

How do you enable constructor overloading?

By having more than one constructor, but each additional constructor must be unique. This means having parameters of different data types, different order of parameters, or a different number of parameters.

How do we access a class-level variable instead of the parameter of a method of the same name?

By using the this keyword. this.name = name; The first name is the instance variable and the "name" contains the value passed in as an argument when the function was invoked

What are class variables?

Class variables are static variables which belong to the class, not the instances of the class. This means there is only one copy of each class variable per class, regardless how many objects there are. Static/class variables can be accessed by referring to the variable on the class: className.variableName

What is compile time?

Compile time is when source code is being converted into bytecode all at once, hence the term compile time.

What is control flow?

Control flow is expressing the order in which your statements should execute. We do this through through special keywords and control flow constructs such as sequences, branching logic, and loops. Most of our programmatic flow is driven by boolean logic - conditions resulting in true or false statements.

What are the four access modifiers in Java?

Default (no keyword required) Private Protected Public

Why is encapsulation important?

Encapsulation helps isolate variables and functions which increases code stability because code is less interdependent. It's a principle of controlling what data is allowed to access other data. For example, if you reuse a variable name, it won't cause issues because the variable has been encapsulated in a class. i.e. the scope is different, so the variable name can be reused. What's more, if you make the data inside a class private, outside functions or variables can't access the properties and methods inside a private class directly. Another benefit of encapsulation is functions have less parameters, since objects already contain the relevant data.

What is encapsulation?

Encapsulation is the principle of containing related states and behavior inside a class and controlling access to them. Inside the class, we can then declare variables and methods and assign a level of accessibility to them, i.e. the four access modifiers: public, private, default, protected The goal of encapsulation is to hide an object's properties and restrict changes to it. This reason is so you don't inadvertently access or modify parts of an object in ways you didn't intend to. e.g. you can make a property private, so it's only accessible within that class, but you can still enable a way to modify them by writing public getter and setter methods if you wish. Another example of encapsulation might be variables defined in a function. Because the variables exist only in local scope, they've been encapsulated and do not exist outside of the function. In other words, scoping is another tool that might enable encapsulation. --------------------------------------- The difference between encapsulation and abstraction is that abstraction focuses on hiding complexity, whereas encapsulation focuses on hiding data.

What are the 8 primitive data types in Java?

Floating Point: - double - float Integral (whole numbers): - byte - short - int - long - char (single Unicode or ASCII character) - boolean (true or false)

When would you need to use the import keyword?

Imports are used when you want to access a class from a different package.

What are packages?

In Java, packages can be thought of as folders/directories. Packages are organizational constructs that group related classes together, i.e. classes that share functionality. (for ex, we can have a package that contains classes that communicate with a database/backend, a package for dealing w/ business logic, etc.) This is meant to keep our programs organized, especially large ones. Like directories, packages can also be nested inside one another. We indicate that a package is a subfolder of another by separating the package names with dots in our package declaration. Like java.util: util is a package inside the java package. For example, a built-in package is java.lang, which contain basic classes like System or String. (Note: java.lang is imported automatically) Another built-in package example is java.util which contains the Scanner class.

What is an operator?

In programming, an operator is a symbol that performs an operation on an object, like a number or a boolean value. For example, the addition symbol, +, is an operator.

What is a benefit of inheritance?

Inheritance helps us eliminate redundant code by enabling code reusability.

What is inheritance?

Inheritance is an object inheriting properties and methods from another class. An object that inherits properties from another class usually represents an IS-A relationship. (Such as a coupe IS A car, which IS a vehicle, etc.) For example, if we define a Car class with the properties engine, wheels, doors, pedals, etc., and we want to pass on those properties for classes representing sedans, SUVs, coupes, etc., then we'll immediately have those properties available and will not have to rewrite them.

What are instance variables?

Instance variables are variables that belong to instances of a class. Each time an instance of a class is created, the system creates one copy of the instance variables related to that class. The opposite of an instance variable is a static variable. A static variable exists across all instances of a class. By default, all variables are created as instance variables.

What will invoking this() do?

Invoking this() can be used to reference another constructor, depending on the data type, order, and number of arguments passed in.

How is Java able to be run anywhere?

It's because of the Java Virtual Machine (JVM). The JVM is built and customized for each platform that supports Java, rather than individual programs or libraries.

Is Java interpreted or compiled?

Java is a hybrid of both. Java source code is first compiled into bytecode which is then interpreted by the JVM, Java Virtual Machine. (Bytecode is a special machine language native to the JVM) This offers the benefit of being able to run anywhere, i.e. being platform agnostic, compared to C++ or Go, where the the generated machine code executables are platform-specific. This is because Just In Time (JIT) compilers turn code into machine native code as the program runs. Thus, interpreted code has no affinity with a particular CPU architecture.

Why Strings are immutable?

Java saves memory by making different variables reference the same String object with the same value instead of creating a new object in memory. This space-saving technique would be for naught if we were able to modify Strings, as it could potentially disrupt a program by changing all the values of variables pointing to the same original String value. Strings are also immutable for security reasons. It would be a security risk if you had malicious code that could change Strings in relation to account holders in banking apps, for example.

What is a static variable?

Like static methods, static variables are variables that belong to the class, not a particular object. This means if we change the value of a static variable in one part of our program, that new value will be used for all references to our static variable throughout the program. This is in opposition to instance variables where each one is unique to the object. There is only one copy of a static variable.

What does method overriding do?

Method Overriding allows you to override your parent class' method and provide a specific implementation for your child class. Method overriding is an example of polymorphism, specifically run-time polymorphism.

What is method overloading?

Method overloading is when a class has multiple methods of the same name, but each has a unique set of parameters. This helps eliminate long if-else chains and switch statements. This enables an object to behave differently depending on the input(s). Method overloading is an example of polymorphism, specifically compile time polymorphism (also called static polymorphism). This is because the argument list is known at compilation, i.e. the compiler already knows which version of method will be invoked before the code is executed.

What is method overriding?

Method overriding is overriding the default functionality of an inherited method from the parent class, in the child class. Method overriding is an example of polymorphism, specifically, runtime polymorphism because we see it when we run our code.

Do you have to explicitly call super() in your constructor?

No - if the super() call is not explicitly provided, the compiler will inject it on the first line automatically. In other words, if absent, super() is invoked implicitly.

Will you still have access to the default no-args constructor if you define your own parameterized one?

No, if you define a parameterized constructor and try to invoke the no-argument constructor, then you will receive an error.

What is an object?

Objects are instances of a class. Meaning, they are an implementation of a class. They have their own copies of states (variables) and behaviors (methods).

What is polymorphism?

Polymorphism allows classes to behave differently via method overloading and method overriding. This is why polymorphism means "many forms", because it allows classes to take on many forms, so to speak.

What is runtime?

Runtime is when the JIT compiler inside the JVM interprets the bytecode into machine code line-by-line and executes it on the specific operating system the JVM is installed on.

What is scope?

Scope is the area in a program where a variable is accessible/visible

What is sequential flow?

Sequential flow is a series of statements executed in order - no decisions or repetitions are made. This is also known as procedural.

What are static methods?

Static methods are methods that are available without needing to instantiate an object. An example of static methods are the methods available in a class like the Math class. We can access Math.floor(), Math.cos(), Math.max(), etc. without creating a Math object.

What's the difference between declaring String literals the instantiating a new String object using the new keyword?

String objects are not stored in the String pool if you declare them with the new keyword. They will be stored outside of the String Pool, but still in the heap. This means you will not be able to use the space-saving technique made possible by the String Pool where it uses shared objects in the String Pool.

Strings are considered what in Java?

Strings are considered Objects, not a primitive data type.

Are strings mutable or immutable?

Strings are immutable because they are backed by a char array which is declared as final in the java.lang package which contains the String class implementation.

What's the difference between switch statements and if-else blocks?

Switch statements do not strictly use conditions that resolve to boolean values to implement logic. Instead, a switch statement is provided a variable expression which is compared against specified case values. For switch statements, the case and variable data types have to match. This means we cannot use relational operators since this would return a boolean, which would not match the case value. A similarity they share is the default case, which acts like the switch statement's else clause.

What's the difference between the Java Runtime Environment and the Java Development Kit?

The Java Runtime Environment contains all the runtime libraries Java programs will need to call and use, and it has the JVM. The Java Development Kit contains the JRE and additional developer tools such as a: - compiler (to transform source code into bytecode) - debugger - documentation tools (JavaDoc) - and other command-line utilities

When is the String Pool created?

The String Pool is defined at compile time, but Strings instantiated using the new keyword will be created at runtime, which is why they will be outside of the String Pool.

Where are Strings stored in memory?

The String Pool, which is in the Heap.

What's the difference between the .equals() method and the equality comparison operator ==?

The comparison operator == is used to check for equality between primitives and Objects. This is why we can't use it for Strings, since two String objects can have the same value but a different address in memory if created using the new keyword. The .equals() operator is strictly for comparing objects, and should be used for objects.

What is a compiler?

The compiler is a program that translates source code into machine code that can be executed by the computer.

What is a constructor?

The constructor is a special method that's used to initialize the attributes of newly created objects of a particular class. The Java compiler will insert a no-argument constructor by default.

What is called when you instantiate an object from a class?

The constructor is called when you create a new object (using the new keyword).

What are some gotchas with switch statements?

The default case usually goes at the bottom like an else in if-else blocks. This means it doesn't need a break since the end of the switch as been reached, however, if you place your default anywhere else it will need a break. You need to provide a break after each case block. Case blocks use the colon : symbol, not curly braces.

When should you use the .equals() method over the equality operator ==?

The equality operator == should be used when comparing values of primitive data types. It checks if two reference variables point to the same object. The .equals() method should be used when comparing objects, such as Strings. It checks if two objects are equivalent but not necessarily the same object. Meaning, it checks if two objects have the same property values instead of comparing to see if they're the same object.

What is the main method?

The main() method is required for all Java applications to compile. The main method serves as the entry point of a Java program. The method signature of main is: public static void main(String args[ ])

What's the purpose of the String Pool?

The purpose of the String pool is to store String objects and if a duplicate String literal is declared, Java does not create a new object, instead, it makes the new variable point to an already existing String object with the same value.

What is a quotient?

The quotient is the numerical result of a division operation. For example, in 10 / 2 = 5 the quotient is 5

Where does static go in a method declaration?

The static keyword comes after the access modifier but before the return type. For example: public static void sayHello() {}

What is the complement of the this keyword?

The super keyword and the this keyword are complements because "this" refers to the current class' methods and variables, whereas "super" refers to the parent class' variables and methods.

What is the this keyword used for?

The this keyword is used to refer to the current class instance, meaning you can use this to refer to the object's instance variables or to invoke the current class methods. An example use case is when you're inside the constructor and initializing the object's properties from the constructor. You would use this.propertyName on the object's instance variables.

What does the void keyword do?

The void keyword means a method does not return anything. Void is an example of a return type. As a reminder, method return types can be: - an object - a primitive - void

What is type casting?

Type casting is data type conversion, usually from a smaller data type to a larger one. For example, say we add two numbers: one with an int data type and one with a double data type. The resulting number will be of type double.

How is upcasting uniquely different from downcasting?

Upcasting is uniquely different in that we do not have to explicitly declare that we want to upcast. Java does it implicitly for us. This is because we can potentially lose data when downcasting.

How are branching control flow structures created?

Using if-else and switch statements, along with conditions that result in boolean values.

What is the difference between while loops and do-while loops?

While loops check its condition before executing, whereas do-while loops check its condition AFTER executing its block of code. Consequently, a do-while loop is guaranteed to run at least once, even if its condition is already false.

Can you have more than one constructor per class?

Yes, you can have more than one constructor per class, but they must possess a unique order or set of parameters. This is known as constructor overloading. Overloading is a form of polymorphism because methods with the same name can behave differently given different arguments.

When should you use a for loop?

You should use a for loop when you know the exact number of times you need to repeat your code block. For example, when you know the length of a collection data structure such as an array, you would want to perform some code for each item in the array.

When should you use a while loop?

You should use a while loop when you're uncertain how many times a block of code should repeat. A while loop will also not execute if the condition is false from the beginning, meaning it's possible for a while loop to never run in a program's life.

How do you import packages?

You use the import keyword. For example: import java.util.Scanner; If we want to use a lot of classes from java.util, we can use the asterisk, like so: import java.util.*

How do you make a class inherit from a superclass?

You use the keyword extends on the intended subclass. Syntax: public class Cybertruck extends Car

What causes the "error: 'void' type not allowed here" message?

You're able to invoke an instance method with a void return type and it can print something, but if you try to print the return value of a method with a void return type, you'll get the "error: 'void' type not allowed here" message. This is because it has no return value.


Set pelajaran terkait

Chemistry B: 1.3 The Nature of Solids

View Set

Ch. 25 Fluid Therapy and Transfusion Medicine

View Set

Workers Compensation Review Quiz

View Set

ISSA Unit 28 EXERCISE AND PREGNANCY

View Set