Unit 2 Objects
public class Main {
int x; // Create a class attribute
// Create a class constructor for the Main class
public Main() {
x = 5; // Set the initial value for the class attribute x
}
public static void main(String[] args) {
Main myObj = new Main(); // Create an object of class Main (This will call the constructor)
System.out.println(myObj.x); // Print the value of x
}
}
public class CheckingAccount{
private int balance;
//An accessor method
public int getBalance(){
return this.balance;
}
//A mutator method
public void setBalance(int newBalance){
this.balance = newBalance;
}
}
public class Main {
int x;
// Constructor with a parameter
public Main(int x) {
this.x = x;
}
// Call the constructor
public static void main(String[] args) {
Main myObj = new Main(5);
System.out.println("Value of x = " + myObj.x);
}
}public class Main {
int x;
// Constructor with a parameter
public Main(int x) {
this.x = x;
}
// Call the constructor
public static void main(String[] args) {
Main myObj = new Main(5);
System.out.println("Value of x = " + myObj.x);
}
}
The toString() will represent any object as a string.
class Student{
int rollno;
String name;
String city;
Student(int rollno, String name, String city){
this.rollno=rollno;
this.name=name;
this.city=city;
}
public static void main(String args[]){
Student s1=new Student(101,"Raj","lucknow");
Student s2=new Student(102,"Vijay","ghaziabad");
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
}
}
String myStr1 = "Hello";
String myStr2 = "Hello";
String myStr3 = "Another String";
System.out.println(myStr1.equals(myStr2)); // Returns true because they are equal
System.out.println(myStr1.equals(myStr3)); // false
A late binding of an object is when the object is determined when the code is ran.
class Animal {
void eat(){System.out.println("animal is eating...");}
}
class Dog extends Animal{
void eat() {
System.out.println("dog is eating...");
}
public static void main(String args[]) {
Animal a=new Dog();
a.eat();
}
}
Polymorphism is how a class is able to provide different implementations of a method. It allows you to make the same action in different ways.
Big O notation is what the set of all the different algorithms that is able to run at a certain speed.
To combine two different strings, you can use concatenation which can combine two or more strings to create one new string.