Study guide v2.0

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

Abstract Method

A method which is declared as abstract and does not have implementation is known as an abstract method. abstract void printStatus(); //no method body and abstract

Types Of Loops

Java programming language provides the following types of loop to handle looping requirements : - While loop - For loop - Do..While loop

String Length

Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object.

What is a String?

Strings, which are widely used in Java programming, are a sequence of characters. In Java programming language, strings are treated as objects. The Java platform provides the String class to create and manipulate strings.

Static Keyword (Java)

The static keyword in Java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than an instance of the class. The static can be: - Variable (also known as a class variable) - Method (also known as a class method) - Block - Nested class

Usage and Rules for Method Overriding

Usage : - Method overriding is used to provide the specific implementation of a method which is already provided by its superclass. - Method overriding is used for runtime polymorphism Rules : - The method must have the same name as in the parent class - The method must have the same parameter as in the parent class. - There must be an IS-A relationship (inheritance).

Object-Oriented Programming (Def)

a methodology or paradigm to design a program using classes and objects.

Default Constructor

a no-arguments(parameters) constructor that the Java compiler inserts on your behalf; it contains a default call to super(); which is the default behavior. If you implement any constructor then you no longer receive a default constructor.

Single Inheritance (code)

class Animal{ void eat( ){System.out.println("eating...");} } class Dog extends Animal{ //Single Inheritance void bark( ){System.out.println("barking...");} } class TestInheritance{ public static void main(String args[ ]){ Dog d=new Dog( ); d.bark( ); d.eat( ); }}

What are the two ways to overload the method in java

- By changing number of arguments - By changing the data type

Advantages of Encapsulation

- By providing only a setter or getter method, you can make the class read-only or write-only. In other words, you can skip the getter or setter methods. - It provides you the control over the data. Suppose you want to set the value of id which should be greater than 100 only, you can write the logic inside the setter method. You can write the logic not to store the negative numbers in the setter methods. - It is a way to achieve data hiding in Java because other class will not be able to access the data through the private data members. - The encapsulate class is easy to test. So, it is better for unit testing.

Rules to remember while creating a constructor:

- Constructor name must be the same as its class name - A Constructor must have no explicit return type - A Java constructor cannot be abstract, static, final, and synchronized

Types of constructors

- Default Constructor - Parameterized Constructor

Encapsulation

- Encapsulation in Java is a process of wrapping code and data together into a single unit, for example, a capsule which is mixed of several medicines. - We can create a fully encapsulated class in Java by making all the data members of the class private. Now we can use setter and getter methods to set and get the data in it. - The Java Bean class is the example of a fully encapsulated class.

Method Overloading

- If a class has multiple methods having same name but different in parameters, it is known as Method Overloading. - If we have to perform only one operation, having same name of the methods increases the readability of the program. - Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be difficult for you as well as other programmers to understand the behavior of the method because its name differs.

Advantages Of Packages

- Java package is used to categorize the classes and interfaces so that they can be easily maintained. - Java package provides access protection. - Java package removes naming collision. Example //save as Simple.java package com.revature; public class Simple{ public static void main(String args[]){ System.out.println("Welcome to package"); } }

Method Overloading (specifics)

- Method overloading is used to increase the readability of the program. - Method overloading is performed within class. - In case of method overloading, parameter must be different. - Method overloading is the example of compile time polymorphism. - In java, method overloading can't be performed by changing return type of the method only. Return type can be same or different in method overloading. But you must have to change the parameter.

Method Overriding (specifics)

- Method overriding is used to provide the specific implementation of the method that is already provided by its super class. - Method overriding occurs in two classes that have IS-A (inheritance) relationship. - In case of method overriding, parameter must be same. - Method overriding is the example of run time polymorphism. - Return type must be same or covariant in method overriding.

Polymorphism

- Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. - Any Java object that can pass more than one IS-A test is considered to be polymorphic. In Java, all Java objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object.

Rules for SWITCH Statement (Java)

- The variable used in a switch statement can only be integers, convertable integers (byte, short, char), strings and enums. - You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon. - The value for a case must be the same data type as the variable in the switch and it must be a constant or a literal. - When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached. - When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement. - Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached. - A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.

Access Modifiers

- There are two types of modifiers in java: access modifiers and non-access modifiers. - The access modifiers in java specifies accessibility (scope) of a data member, method, constructor or class. There are 4 types of java access modifiers: - private - default - protected - public There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient etc. Here, we will learn access modifiers.

Loops In Java

- There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. - Programming languages provide various control structures that allow for more complicated execution paths. - A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages.

Object

- can be defined as an instance of a class. An object contains an address and takes up some space in memory. - can communicate without knowing the details of each other's data or code. The only necessary thing is the type of message accepted and the type of response returned by the objects. Example: A dog is _________ because it has states like color, name, breed, etc. as well as behaviors like wagging the tail, barking, eating, etc.

Class

- in the context of Java, are templates that are used to create objects, and to define object data types and methods. Core properties include the data types and methods that may be used by the object - can also be defined as a blueprint from which you can create an individual object. It doesn't consume any space.

Method bullets

- is used to expose the behavior of an object. - must have a return type. - is invoked EXPlicitly. - is not provided by the compiler in any case. - The name may or may not be same as class name.

Constructor bullets

- is used to initialize the state of an object. - must not have a return type. - is invoked IMPlicitly. - The Java compiler provides a default if you don't have any constructor in a class. - The name must be same as the class name.

4 types of java access modifiers

- private - default - protected - public

Read-Only Class (code)

//A Java class which has only getter methods. public class Student{ //private data member private String college="AKG"; //getter method for college public String getCollege(){ return college; } } The above class is an example of a Read-Only class because it has only a getter to access the college name. If the user tries to change the value of the college name, a compile-time error is rendered.

Write-Only Class (code)

//A Java class which has only setter methods. public class Student{ //private data member private String college; //getter method for college public void setCollege(String college){ this.college=college; } } The above class is an example of a Write-Only class because it has only setters to change the value of the college name and cannot read the college name. Even if tried to access outside of this class a compile-time error is displayed only because the variable is declared as private.

Abstract Class

A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.

Parameterized Constructor (More Research)

A constructor which has a specific number of parameters is called a parameterized constructor. The parameterized constructor is used to provide different values to the distinct objects. However, you can provide the same values also. class Student4{ int id; String name; Student4(int i,String n){ id = i; name = n; } void display(){System.out.println(id+" "+name);} public static void main(String args[ ]){ Student4 s1 = new Student4(111,"Karan"); Student4 s2 = new Student4(222,"Aryan"); s1.display(); s2.display(); } } In the above example, we have created the constructor of Student class that have two parameters(name, id). We can have any number of parameters in the constructor.

Do..While Loop (Java)

A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time. Syntax : do { // Statements }while(Boolean_expression); Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once before the Boolean is tested. If the Boolean expression is true, the control jumps back up to do statement, and the statements in the loop execute again. This process repeats until the Boolean expression is false.

For Loop (java)

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to be executed a specific number of times. A for loop is useful when you know how many times a task is to be repeated. Syntax : for(initialization; Boolean_expression; update) { // Statements } This is how it works : The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables and this step ends with a semi colon (;). Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop will not be executed and control jumps to the next statement past the for loop. After the body of the for loop gets executed, the control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank with a semicolon at the end. The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats (body of loop, then update step, then Boolean expression). After the Boolean expression is false, the for loop terminates.

Package

A java package is a group of similar types of classes, interfaces and sub-packages. Package in java can be categorized in two form, built-in package and user-defined package. There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

SWITCH Statement (Java)

A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case. Syntax : switch(expression) { case value : // Statements break; // optional case value : // Statements break; // optional // You can have any number of case statements. default : // Optional // Statements }

While Loop (java)

A while loop statement in Java programming language repeatedly executes a target statement as long as a given condition is true. Syntax : while(Boolean_expression) { // Statements } Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non zero value. When executing, if the boolean_expression result is true, then the actions inside the loop will be executed. This will continue as long as the expression result is true. When the condition becomes false, program control passes to the line immediately following the loop.

Abstraction

Abstraction is a process of hiding the implementation details and showing only functionality to the user. Another way, it shows only essential things to the user and hides the internal details, for example, sending SMS where you type the text and send the message. You don't know the internal processing about the message delivery. Abstraction lets you focus on what the object does instead of how it does it.

IF..ELSE IF Statement (Java)

An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement. When using if, else if, else statements there are a few points to keep in mind. - An if can have zero or one else's and it must come after any else if's. - An if can have zero to many else if's and they must come before the else. - Once an else if succeeds, none of the remaining else if's or else's will be tested. Syntax : if(Boolean_expression 1) { // Executes when the Boolean expression 1 is true }else if(Boolean_expression 2) { // Executes when the Boolean expression 2 is true }else if(Boolean_expression 3) { // Executes when the Boolean expression 3 is true }else { // Executes when the none of the above condition is true. }

IF..ELSE Statement (Java)

An if statement can be followed by an optional else statement, which executes when the Boolean expression is false. Syntax : if(Boolean_expression) { // Executes when the Boolean expression is true }else { // Executes when the Boolean expression is false }

IF Statement (Java)

An if statement consists of a Boolean expression followed by one or more statements. Syntax : if(Boolean_expression) { // Statements will execute if the Boolean expression is true } If the Boolean expression evaluates to true then the block of code inside the if statement will be executed. If not, the first set of code after the end of the if statement (after the closing curly brace) will be executed.

Enhanced For Loop

As of Java 5, the enhanced for loop was introduced. This is mainly used to traverse collection of elements including arrays. Syntax : for(declaration : expression) { // Statements } Declaration − The newly declared block variable, is of a type compatible with the elements of the array you are accessing. The variable will be available within the for block and its value would be the same as the current array element. Expression − This evaluates to the array you need to loop through. The expression can be an array variable or method call that returns an array.

Terms used in Inheritance

Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class. Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class. Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class.

Constructor vs Method

Constructor : - A constructor is used to initialize the state of an object. - A constructor must not have a return type. - The constructor is invoked implicitly. - The Java compiler provides a default constructor if you don't have any constructor in a class. - The constructor name must be same as the class name. Method : - A method is used to expose the behavior of an object. - A method must have a return type. - The method is invoked explicitly. - The method is not provided by the compiler in any case. - The method name may or may not be same as class name.

Decision Making Structures (conditionals)

Decision making structures have one or more conditions to be evaluated or tested by the program, along with a statement or statements that are to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Java programming language provides following types of decision making statements. - if statement - if..else statement - nested if statement - switch statement

Final Method (code example)

Final Method : class Bike{ final void run(){System.out.println("running");} } class Honda extends Bike{ void run(){System.out.println("running safely with 100kmph");} // Compile Time Error (Cant override final method) public static void main(String args[]){ Honda honda= new Honda(); honda.run(); } }

Advantages of Inheritance

For Method Overriding (so runtime polymorphism can be achieved). For Code Reusability.

Generalization

Generalization is the process of extracting shared characteristics from two or more classes, and combining them into a generalized superclass. Shared characteristics can be attributes, associations, or methods. Eg : The classes Piece of Luggage and Piece of Cargo partially share the same attributes. From a domain perspective, the two classes are also very similar. During generalization, the shared characteristics are combined and used to create a new superclass Freight . Piece of Luggage and Piece of Cargo become subclasses of the class Freight. Therefore the properties that are common to the classes Piece of Luggage and Piece of Cargo are placed in the superclass Freight - Identification, Weight and ID-Number are those properties.

Method Overriding

If a subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java. In other words, If a subclass provides the specific implementation of the method that has been declared by one of its parent class, it is known as method overriding.

Static variable (Java)

If you declare any variable as static, it is known as a static variable. The static variable can be used to refer to the common property of all objects (which is not unique for each object), for example, the company name of employees, college name of students, etc. The static variable gets memory only once in the class area at the time of class loading. Advantages It makes your program memory efficient (i.e., it saves memory). Example //Java Program to demonstrate the use of static variable class Student{ int rollno;//instance variable String name; static String college ="ITS"; //static variable //constructor Student(int r, String n){ rollno = r; name = n; } //method to display the values void display (){System.out.println(rollno+" "+name+" "+college);} } //Test class to show the values of objects public class TestStaticVariable1{ public static void main(String args[]){ Student s1 = new Student(111,"Karan"); Student s2 = new Student(222,"Aryan"); //we can change the college of all objects by the single line of code //Student.college="BBDIT"; s1.display(); s2.display(); } }

Constructor Overloading

In Java, a constructor is just like a method but without return type. It can also be overloaded like Java methods. Constructor overloading in Java is a technique of having more than one constructor with different parameter lists. They are arranged in a way that each constructor performs a different task. They are differentiated by the compiler by the number of parameters in the list and their types. class Student5{ int id; String name; int age; //creating two argument constructor Student5(int i,String n){ id = i; name = n; } //creating three argument constructor Student5(int i,String n,int a){ id = i; name = n; age=a; } void display(){System.out.println(id+" "+name+" "+age);} public static void main(String args[]){ Student5 s1 = new Student5(111,"Karan"); Student5 s2 = new Student5(222,"Aryan",25); s1.display(); s2.display(); } }

Object Oriented Programming Pillars

Inheritance Abstraction Polymorphism Encapsulation

Nested IF Statement (Java)

It is always legal to nest if-else statements which means you can use one if or else if statement inside another if or else if statement. Syntax : if(Boolean_expression 1) { // Executes when the Boolean expression 1 is true if(Boolean_expression 2) { // Executes when the Boolean expression 2 is true } }

Method Overloading vs Method Overriding

Method Overloading : - Method overloading is used to increase the readability of the program. - Method overloading is performed within class. - In case of method overloading, parameter must be different. - Method overloading is the example of compile time polymorphism. - In java, method overloading can't be performed by changing return type of the method only. Return type can be same or different in method overloading. But you must have to change the parameter. Method Overriding : - Method overriding is used to provide the specific implementation of the method that is already provided by its super class. - Method overriding occurs in two classes that have IS-A (inheritance) relationship. - In case of method overriding, parameter must be same. - Method overriding is the example of run time polymorphism. - Return type must be same or covariant in method overriding.

Can a static method be overridden?

No, a static method cannot be overridden. It can be proved by runtime polymorphism, so we will learn it later. It is because the static method is bound with class whereas instance method is bound with an object. Static belongs to the class area, and an instance belongs to the heap area.

Advantages of OOPs over Procedure Oriented Programming

OOPs makes development and maintenance easier whereas in a procedure-oriented programming language it is not easy to manage if code grows as project size increases. OOPs provides data hiding whereas in a procedure-oriented programming language a global data can be accessed from anywhere. `public class Dog { String breed; int age; String color; void barking() { } void hungry() { } void sleeping() { } } ` A class is a blueprint from which individual objects are created. The code above is a sample of a class Dog with attributes and behavior.

Types Of Inheritance In Java

On the basis of class, there can be three types of inheritance in java: - single - multilevel - hierarchical. In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces later.

Specialization

Specialization means creating new subclasses from an existing class. If it turns out that certain attributes, associations, or methods only apply to some of the objects of the class, a subclass can be created. In the previous example for Generalization, we saw that the classes Piece of Luggage and Piece of Cargo shared similar properties that were placed in a superclass called Freight. When it comes to Specialization, if there is a property that is only applicable to a specific subclass, such as Degree of Hazardousness, that property is placed in the class Piece of Cargo where-in this class also has all the properties of the Freight class with the concept of Generalization.

Concatenating Strings

The String class includes a method for concatenating two strings : string1.concat(string2); This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method with string literals "My Name is".concat("Zara"); Strings are most commonly concatenated with the "+" operator "Hello," + " world" + "!"

Final Keyword

The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be: variable method class The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only.

Creating Strings

The most direct way to create a string is to write : String greeting = "hello world"; Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case, "Hello world!'. As with any other object, you can create String objects by using the new keyword and a constructor. The String class has 11 constructors that allow you to provide the initial value of the string using different sources, such as an array of characters.

Using "super" to invoke parent class method (Java)

The super keyword can also be used to invoke parent class method. It should be used if subclass contains the same method as parent class. In other words, it is used if method is overridden. class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ void eat(){System.out.println("eating bread...");} void bark(){System.out.println("barking...");} void work(){ super.eat(); // Calling the parent class eat() method using super keyword bark(); } } class TestSuper2{ public static void main(String args[]){ Dog d=new Dog(); d.work(); }}

Using "super" to invoke parent class constructor (Java)

The super keyword can also be used to invoke the parent class constructor. class Animal{ Animal(){System.out.println("animal is created");} } class Dog extends Animal{ Dog(){ super(); // using super keyword to access the parent class constructor. System.out.println("dog is created"); } } class TestSuper3{ public static void main(String args[]){ Dog d=new Dog(); }} Note : While using "super" keyword to access the parent class constructor, remember that it has to be in the first line within the subclass constructor.

Usage of "super" keyword (Java)

The super keyword in Java is a reference variable which is used to refer immediate parent class object. Whenever you create the instance of subclass, an instance of parent class is created implicitly which is referred by super reference variable. super can be used to refer immediate parent class instance variable. super can be used to invoke immediate parent class method. super( ) can be used to invoke immediate parent class constructor.

"this" : to refer current class instance variable (java)

The this keyword can be used to refer current class instance variable. If there is ambiguity between the instance variables and parameters, this keyword resolves the problem of ambiguity. class Student{ int rollno; String name; float fee; Student(int rollno,String name,float fee){ this.rollno=rollno; // Refers class instance variable rollno this.name=name; // Refers class instance variable name this.fee=fee; // Refers class instance variable fee } void display(){System.out.println(rollno+" "+name+" "+fee);} } class TestThis2{ public static void main(String args[]){ Student s1=new Student(111,"ankit",5000f); Student s2=new Student(112,"sumit",6000f); s1.display(); s2.display(); }}

"this" : to invoke current class constructor (Java)

The this() constructor call can be used to invoke the current class constructor. It is used to reuse the constructor. In other words, it is used for constructor chaining. Example class A{ A(){System.out.println("hello a");} A(int x){ this(); // Current class constructor is called. System.out.println(x); } } class TestThis5{ public static void main(String args[]){ A a=new A(10); }}

Accessing a package from other packages

There are three ways to access the package from outside the package. - import package.*; - import package.classname; - fully qualified name.

Ways to achieve abstraction?

There are two ways to achieve abstraction in java - Abstract class (0 to 100%) - Interface (100%)

Different ways to overload a method?

There are two ways to overload the method in java: - By changing number of arguments - By changing the data type

Usage of "this" keyword (Java)

There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to the current object. Here is given the 6 usage of java this keyword: - this can be used to refer current class instance variable. - this can be used to invoke current class method (implicitly) - this( ) can be used to invoke current class constructor. - this can be passed as an argument in the method call. - this can be passed as argument in the constructor call. - this can be used to return the current class instance from the method.

Why multiple inheritance is not supported in Java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in java. Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the same method and you call it from child class object, there will be ambiguity to call the method of A or B class. Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error. class A{ void msg( ){System.out.println("Hello");} } class B{ void msg( ){System.out.println("Welcome");} } class C extends A,B{ //suppose if it were public static void main(String args[ ]){ C obj=new C( ); obj.msg( ); //Now which msg() method would be invoked? } }

Using "super" to refer parent class instance variable (Java)

We can use super keyword to access the data member or field of parent class. It is used if parent class and child class have same fields. class Animal{ String color="white"; } class Dog extends Animal{ String color="black"; void printColor(){ System.out.println(color); //prints color of Dog class System.out.println(super.color); //prints color of Animal class } } class TestSuper1{ public static void main(String args[]){ Dog d=new Dog(); d.printColor(); }}

When is a constructor called?

When an object is created, compiler makes sure that constructors for all of its sub-objects (its member and inherited objects) are called. If members have default constructors or constructor without parameter then these constructors are called automatically, otherwise parameterized constructors can be called using initializer list. Note: It is called constructor because it constructs the values at the time of object creation. It is not necessary to write a constructor for a class. It is because java compiler creates a default constructor if your class doesn't have any.

Usage of the "new" keyword (Java)

When you are declaring a class in java, you are just creating a new data type. A class provides the blueprint for objects. You can create an object from a class. Declaration : First, you must declare a variable of the class type. This variable does not define an object. Instantiation and Initialization : Second, you must acquire an actual, physical copy of the object and assign it to that variable. You can do this using the new operator. The new operator instantiates a class by dynamically allocating(i.e, allocation at run time) memory for a new object and returning a reference to that memory. This reference is then stored in the variable. Thus, in Java, all class objects must be dynamically allocated. The new operator is also followed by a call to a class constructor, which initializes the new object. A constructor defines what occurs when an object of a class is created. Constructors are an important part of all classes and have many significant attributes. Example Let us say that we have a class called Student and we need to instantiate this class. The following syntax does that : Student anil = new Student();

"this" : to invoke current class method (java)

You may invoke the method of the current class by using the this keyword. If you don't use the this keyword, compiler automatically adds this keyword while invoking the method. class A{ void m(){System.out.println("hello m");} void n(){ System.out.println("hello n"); //m();//same as this.m() this.m(); // By default added by the compiler } } class TestThis4{ public static void main(String args[]){ A a=new A(); a.n(); }}

Constructor

a block of codes similar to the method. It is called when an instance of the object is created, and memory is allocated for the object. It is a special type of method which is used to initialize the object.

Object (simple)

a real-world entity such as a pen, chair, table, computer, watch, etc

Example of Abstract Class with an Abstract Method (code)

abstract class Bike{ // Abstract class abstract void run(); // Abstract method } class Honda4 extends Bike{ void run(){System.out.println("running safely");} public static void main(String args[]){ Bike obj = new Honda4(); obj.run(); } }

Some String Handling Methods

char charAt(int index) - Returns the character at the specified index. int compareTo(Object o) - Compares this String to another Object. String concat(String str) - Concatenates the specified string to the end of this string. boolean equals(Object anObject) - Compares this string to the specified object. boolean equalsIgnoreCase(String anotherString) - Compares this String to another String, ignoring case considerations.

Example for Method Overriding (code)

class ABC{ //Overridden method public void disp() { System.out.println("disp( ) method of parent class"); } } class Demo extends ABC{ //Overriding method public void disp( ){ System.out.println("disp( ) method of Child class"); } public void newMethod( ){ System.out.println("new method of child class"); } public static void main( String args[ ]) { ABC obj = new ABC( ); obj.disp( ); ABC obj2 = new Demo( ); // Covariance with reference types obj2.disp( ); } } In the above example, we have defined the disp( ) method in the subclass as defined in the parent class but it has some specific implementation. The name and parameter list of the methods are the same, and there is IS-A relationship between the classes.

Method Overloading - Changing data type of arguments (code)

class Adder{ static int add(int a, int b){return a+b;} // 2 arguments of int data type static double add(double a, double b){return a+b;} // 2 arguments of double data type } class TestOverloading2{ public static void main(String[] args){ System.out.println(Adder.add(11,11)); System.out.println(Adder.add(12.3,12.6)); }} In the above example, we have created two methods that differs in data type. The first add method receives two integer arguments and second add method receives two double arguments. Note : Method overloading is not possible by changing the return type of the method.

Method Overloading - Changing the number of arguments (code)

class Adder{ static int add(int a,int b){return a+b;} // 2 arguments static int add(int a,int b,int c){return a+b+c;} //3 arguments } class TestOverloading1{ public static void main(String[ ] args){ System.out.println(Adder.add(11,11)); System.out.println(Adder.add(11,11,11)); }} In the above example, we have created two methods, first add( ) method performs addition of two numbers and second add method performs addition of three numbers. In the above example, we are creating static methods so that we don't need to create instance for calling methods.

Hierarchical Inheritance (code)

class Animal{ void eat( ){System.out.println("eating...");} } class Dog extends Animal{ // Hierarchical Inheritance void bark( ){System.out.println("barking...");} } class Cat extends Animal{ // Hierarchical Inheritance void meow( ){System.out.println("meowing...");} } class TestInheritance3{ public static void main(String args[ ]){ Cat c=new Cat( ); c.meow( ); c.eat( ); //c.bark( ); //Error }}

Multilevel Inheritance (code)

class Animal{ void eat( ){System.out.println("eating...");} } class Dog extends Animal{ //Level 1 - Inheritance void bark( ){System.out.println("barking...");} } class BabyDog extends Dog{ //Level 2 - Inheritance void weep( ){System.out.println("weeping...");} } class TestInheritance2{ public static void main(String args[ ]){ BabyDog d=new BabyDog( ); d.weep( ); d.bark( ); d.eat( ); }}

Access Modifiers with Method Overriding

class A{ protected void msg(){System.out.println("Hello java");} } public class Simple extends A{ void msg( ){System.out.println("Hello java");} // Error because Class Simple method msg( ) is more restrictive that Class A method msg( ) public static void main(String args[]){ Simple obj=new Simple(); obj.msg(); } } If you are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive.

Final Variable (code example)

class Bike9{ final int speedlimit=90;//final variable void run(){ speedlimit=400; // Compile Time Error (Cant change final variable value) } public static void main(String args[]){ Bike9 obj=new Bike9(); obj.run(); } }//end of class

Example of Inheritance (with code)

class Employee{ float salary=40000; } class Programmer extends Employee{ int bonus=10000; public static void main(String args[]){ Programmer p=new Programmer(); System.out.println("Programmer salary is:"+p.salary); System.out.println("Bonus of Programmer is:"+p.bonus); } } Figure: Employee ------------- salary: float ------------- ^ | ------------- Programmer --------------- bonus: int As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The relationship between the two classes is Programmer IS-A Employee. It means that Programmer is a type of Employee.

Syntax of Inheritance (code)

class Subclass-name extends Superclass-name { //methods and fields added here } The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of "extends" is to increase the functionality.

Overloading the main( ) method in Java (code)

class TestOverloading4{ public static void main(String[ ] args){System.out.println("main with String[ ]");} public static void main(String args){System.out.println("main with String");} public static void main( ){System.out.println("main without args");} } Yes, by method overloading. You can have any number of main methods in a class by method overloading. But JVM calls main( ) method which receives string array as arguments only.

Final Class (code example)

final class Bike{} class Honda1 extends Bike{ // Compile Time Error (Cant extend final class) void run(){System.out.println("running safely with 100kmph");} public static void main(String args[]){ Honda1 honda= new Honda1(); honda.run(); } }

What are the three ways to access the package from outside the package?

import package.*; import package.classname; fully qualified name.

Inheritance

in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of OOPs (Object Oriented programming system). The idea behind this in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also. represents the IS-A relationship which is also known as a parent-child relationship.

Example for Encapsulation (code)

package com.revature; public class Student{ //private data member private String name; //getter method for name public String getName(){ return name; } //setter method for name public void setName(String name){ this.name=name } } //A Java class to test the encapsulated class. package com.revature; class Test{ public static void main(String[] args){ //creating instance of the encapsulated class Student s=new Student(); //setting value in the name member s.setName("vijay"); //getting value of the name member System.out.println(s.getName()); } } The above is an example of encapsulation of a class called Student that has only one field with its setter and getter methods.

No-Argument Constructor (More Research)

public Bicycle() { gear = 1; cadence = 10; speed = 0; } Bicycle yourBike = new Bicycle(); invokes the no-argument constructor to create a new Bicycle object called yourBike.

Creating strings (code example)

public class StringDemo { public static void main(String args[ ]) { char[ ] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' }; String helloString = new String(helloArray); System.out.println( helloString ); } } Note : The String class is immutable, so that once it is created a String object cannot be changed. If there is a necessity to make a lot of modifications to Strings of characters, then you should use String Buffer & String Builder Classes.

String length (code example)

public class StringDemo { public static void main(String args[]) { String palindrome = "Dot saw I was Tod"; int len = palindrome.length(); // Using the length method System.out.println( "String Length is : " + len ); } }

Concatenating strings (code example)

public class StringDemo { public static void main(String args[]) { String string1 = "saw I was "; System.out.println("Dot " + string1 + "Tod"); } }

Enhanced For Loop (Java code example)

public class Test { public static void main(String args[ ]) { int [ ] numbers = {10, 20, 30, 40, 50}; for(int x : numbers ) { System.out.print( x ); System.out.print(","); } System.out.print("\n"); String [] names = {"James", "Larry", "Tom", "Lacy"}; for( String name : names ) { System.out.print( name ); System.out.print(","); } } }

For Loop (Java code example)

public class Test { public static void main(String args[]) { for(int x = 10; x < 20; x = x + 1) { System.out.print("value of x : " + x ); System.out.print("\n"); } } }

Do..While Loop ( Java code example)

public class Test { public static void main(String args[]) { int x = 10; do { System.out.print("value of x : " + x ); x++; System.out.print("\n"); }while( x < 20 ); } }

Object-Oriented Programming (Concepts)

simplifies the software development and maintenance by providing some concepts: - Object - Classes - Inheritance - Polymorphism - Abstraction - Encapsulation


संबंधित स्टडी सेट्स

Chapter 44: Nursing Care of the Child With an Alteration in Mobility/Neuromuscular or Musculoskeletal Disorder

View Set

Intro to weather and climate exam #2 on chapters 4-5

View Set