Creating Class and Child Class with extends- Example0007
Using 'extends' keyword to create a child Class- IS-A relation.We 'extend' a child Class with IS-A relation. Child Class will have all the methods and attributes.
The child can have additional attributes or methods. But that is for another example
Keyword: java, extends, inheritance, IS-A, IS-A relation, child class, parent class, sub class, parent class
package com.swprogramdeveloper;
//Textual presentation of an object, how it will look like in the memory
//Whatever we write in class is actually belong to object. Note: if you want something for class, need to write static
class Product {
//Attribute
int pid;
String name;
int price;
//Constructor
Product() {
System.out.println(">>Product Object Constructed");
}
//Methods
//Method one to initialize data
void setProductDetails(int pid, String name, int price){
this.pid=pid;
this.name=name;
this.price=price;
}
//Method to display data
void showProductDetails(){
System.out.println("-----Product ID: "+pid+"----------");
System.out.println("Name:\t"+name);
System.out.println("Price:\t"+price);
System.out.println("---------------------------");
}
}
//IS-A relation and extends
class Mobile extends Product {
// Constructor
Mobile() {
System.out.println("--Mobile Constructor created---");
}
}
public class Main {
public static void main(String[] args) {
// Creating class from extended class
System.out.println("---Output of extended mobile class from product----");
Mobile mobile1 = new Mobile();
mobile1.setProductDetails(980,"mi note2",23000);
mobile1.showProductDetails();
}
}
Output0007
=======
---Output of extended mobile class from product----
>>Product Object Constructed
--Mobile Constructor created---
-----Product ID: 980----------
Name: mi note2
Price: 23000
---------------------------
Process finished with exit code 0
Comments
Post a Comment